Reputation: 1
I have successfully allocated dataframe names and populated them (see code) but I do not know how to subsequently reference them. So I loop through to assign df.test1
and populate it with some data 1
and so on. I know that the df
has been created, and can view or summary it in the console, but not in the code.
I am pretty new to R
so am not sure if some of the solutions I have looked at apply to me.
num.clusters <- 5
for (i in 1:num.clusters) {
assign(paste("df.test",i,sep=""), paste("somedata", i))
}
This works but Then want to do something like:
View(df.test,i)
to view whatever iteration from 1
to 5
.
I want to be able to use the assigned dataframes like any other dataframe. I could hard code this as View(df.test1)
but that would defeat the point. I also want to do other things with the datframe
, e.g. subsetting.
I know this doesn't work. Would love to know what does.
Many thanks...
Upvotes: 0
Views: 337
Reputation: 325
Your question is the proof that the approach is problematic: avoid using assign
in general because it makes accessing the variables afterwards awkward (among other issues).
A cleaner way is to just put your "data frames" (copying from your example) in a list:
num.clusters <- 5
df.test <- list()
for (i in 1:num.clusters) {
df.test[[i]] <- paste("somedata", i)
}
Then you would just access them like this:
View(df.test[[i]])
If what you put in there was an actual data.frame
(and not the strings you were using), you could then access its columns like any other data.frame
:
df.test[[i]]$Name
Or
df.test[[i]][, "Name"]
Upvotes: 1