Referencing an existing data frame with a dynamica

2019-08-31 00:39发布

问题:

This feels like this should have a simple solution but it eludes me.

I have an existing set of data frames, called set1, set2, and set3. I want to merge each of them - separately - with another data frame, like so:

a <- merge(bigdata, set1, by = keyID)
b <- merge(bigdata, set2, by = keyID)
c <- merge(bigdata, set3, by = keyID)
...

I want to reference the existing 'sets' on the fly (in a loop), so I made this object:

nam <- paste('set', i, sep = '')

Of course, if I do this:

> nam

I get this:

> "set1"

But I want to use that "set1" reference to represent the apprpopriate data frame up in the merging code, not just an object of class "chr." Any help is, as always, appreciated.

回答1:

You could use get as Juba suggested, or you make an input list.

 bigset<-list(set1=set1,set2=set2, [etc)
 abc_list <- sapply(1:length(bigset) function(j) merge(bigdata,bigset[[j]])

and you're done. Alternatively, without creating bigset,

setnames<-ls(pattern='set[0-9]{1,})
abc_list<-sapply(1:length(setnames), function(j) merge(bigdata,get(setnames[j]))


标签: r merge assign