Nathaniel Saxe
Nathaniel Saxe

Reputation: 1555

add a data frame to a constructed name

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

}

Upvotes: 1

Views: 384

Answers (2)

Greg
Greg

Reputation: 11764

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
...

Upvotes: 0

nullglob
nullglob

Reputation: 7023

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

Upvotes: 7

Related Questions