nopeva
nopeva

Reputation: 1605

How to assign values to dynamic names variables

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
}

Upvotes: 21

Views: 49667

Answers (2)

Karsten W.
Karsten W.

Reputation: 18400

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])

Upvotes: 12

Jilber Urbina
Jilber Urbina

Reputation: 61154

use assign as in:

x <- 1:10

for(i in seq_along(x)){
  assign(paste('X', i, sep=''), x[i])
}

Upvotes: 34

Related Questions