tags:

views:

52

answers:

2

I have this

for(i in 1:10)

and within it, I have a data frame: e.g.

df<-1:100

and I want to assign the dataframe to a specific name which I want to create

something like: (not that it works)

paste("name", variable[i])<- df

Edit:

How would I then go about accessing those constructed values in another loop (assuming i've used assign)

    datalist <- paste("a",1:100,sep="")
    for (i in 1:length(datalist)){

}
+4  A: 

I suggest assign, as illustrated here:

for(i in 1:100){
  df <- data.frame(x = rnorm(10),y = rpois(10,10))
  assign(paste('df',i,sep=''),df)
}
nullglob
Do you know how I would be able to access those assigned values in another loop?
Nathaniel Saxe
@Nathaniel `get(paste('df',i,sep=''))` But if you need it you could use list instead. `list_of_df <- lapply(1:100, function(i) data.frame(...))` and then in another loop/lapply use `list_of_df[[i]]`.
Marek
@Marek oh cool, thanks!
Nathaniel Saxe
A: 

You could store the output of your loop in a list:

set.seed(10)
x = list()

for(i in 1:10){
  x[[i]] <- data.frame(x = rnorm(100), y = rnorm(100))
  }

Then x will be a list of length 10 and each element of the list will be of dim c(100, 2)

> length(x)
[1] 10
> dim(x[[1]])
[1] 100   2
> 

Of course you could name the elements of the list, as well:

names(x) = letters[1:10]

x[["a"]]


              x           y
1    0.01874617 -0.76180434
2   -0.18425254  0.41937541
3   -1.37133055 -1.03994336
4   -0.59916772  0.71157397
5    0.29454513 -0.63321301
6    0.38979430  0.56317466
...
Greg