Referencing an existing data frame with a dynamically-created character object

放肆的年华 提交于 2019-12-25 01:41:09

问题


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


来源:https://stackoverflow.com/questions/26179590/referencing-an-existing-data-frame-with-a-dynamically-created-character-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!