tags:

views:

245

answers:

3

Is it possible to create new variable names on the fly?

I'd like to read data frames from a list into new variables with numbers at the end. Something like orca1, orca2, orca3...

If I try something like

paste("orca",i,sep="")=list_name[[i]]

I get this error

target of assignment expands to non-language object

Is there another way around this?

+9  A: 

Use assign:

 assign(paste("orca",i,sep=""), list_name[[i]])
Shane
+2  A: 

It seems to me that you might be better off with a list rather than using orca1, orca2, etc... then it would be orca[1], orca[2]...

Usually you're making a list of variables differentiated by nothing but a number because that number would be a convenient way to access them later.

orca <- list() orca[1] <- "Hi" orca[2] <- 59

Otherwise, "assign" is just what you want

John
I agree. Usually when people think they want to name variables on the fly, what they really want is a different data structure.
Michael Dunn
A: 

Another tricky solution is to name elements of list and attach it:

list_name = list(
    head(iris),
    head(swiss),
    head(airquality)
    )

names(list_name) <- paste("orca", seq_along(list_name), sep="")
attach(list_name)

orca1
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa
Marek