3

I'm creating data frames within a loop. The data frames' name should be the combination of a name and a number (the loops iteration). I use the assign function for this and works. I also want to assign names to the data frames' rows. I tried two ways, but I'm getting the error messages "target of assignment expands to non-language object" and "only the first element is used as variable name". Below is a reproducible example of I'm trying to do.

rows<-c("a","b")
df<-data.frame(var1=c(1,2),var2=c(10,20))
for (n in 1:2){
  assign  (paste("data",n,sep="_"),df)
  rownames(get(paste("data",n,sep="_")))<-rows        # it doesn't work
  assign(rownames(get(paste("data",n,sep="_"))),rows) # it doesn't work
}

I'd like to know why it doesn't work and how to solve it. I found similar threads like this and this, but I was not able to solve my case. Thank you.

Community
  • 1
  • 1
Hugo
  • 357
  • 3
  • 10
  • This has been asked here many times. The answer is always "don't do that". Instead put your data.frames in a list. – Roland Oct 31 '14 at 19:47

2 Answers2

1

Based on Roland's comment, I come out with this solution:

rows<-c("a","b")
df<-data.frame(var1=c(1,2),var2=c(10,20))
dfs<-list()
for (n in 1:2){
  dfs[[n]]<-df
  rownames(dfs[[n]])<-rows
}

A list is the key!

Hugo
  • 357
  • 3
  • 10
0

Or without list, you just need a dummy variable:

rows<-c("a","b")
df<-data.frame(var1=c(1,2),var2=c(10,20))
for (n in 1:2){
  assign  (paste("data",n,sep="_"),df)
  labelling <- get(paste("data",n,sep="_"))
  labels <- rows
  rownames(labelling)<-labels
  assign(paste("data",n,sep="_"),labelling)
}