Hi I'm trying to name variables using a for loop so I get dynamic names for my variables.
for (i in 1:nX) {
paste("X",i, sep="")=datos[,i+1]
next
}
Use the for Loop to Create a Dynamic Variable Name in Python The globals() method in Python provides the output as a dictionary of the current global symbol table. The following code uses the for loop and the globals() method to create a dynamic variable name in Python. Output: Copy Hello from variable number 5!
There are no dynamic variables in Java. Java variables have to be declared in the source code1. Depending on what you are trying to achieve, you should use an array, a List or a Map ; e.g. It is possible to use reflection to dynamically refer to variables that have been declared in the source code.
use assign
as in:
x <- 1:10
for(i in seq_along(x)){
assign(paste('X', i, sep=''), x[i])
}
It can be a good idea to use assign
when there are many variables and they are looked up frequently. Lookup in an environment is faster than in vector or list. A separate environment for the data objects is a good idea.
Another idea is to use the hash
package. It performs lookup as fast as environments, but is more comfortable to use.
datos <- rnorm(1:10)
library(hash)
h <- hash(paste("x", 1:10, sep=""), datos)
h[["x1"]]
Here is a timing comparision for 10000 vars that are looked up 10^5 times:
datos <- rnorm(1:10000)
lookup <- paste("x", sample.int(length(datos), 100000, replace=TRUE), sep="")
# method 1, takes 16s on my machine
names(datos) <- paste("x", seq_along(datos), sep="")
system.time(for(key in lookup) datos[[key]])
# method 2, takes 1.6s on my machine
library(hash)
h <- hash(paste("x", seq_along(datos), sep=""), datos)
system.time(for(key in lookup) h[[key]])
# method 3, takes 0.2s on my machine
e <- new.env()
for(i in seq_along(datos)){
assign(paste('x', i, sep=''), datos[i], envir=e)
}
system.time(for(key in lookup) e[[key]])
However, the vectorized version of method 1 is the fastest, but is not always applicable
# method 4, takes 0.02s
names(datos) <- paste("x", seq_along(datos), sep="")
system.time(datos[lookup])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With