当表名是变量时更新列值

时间:2014-06-02 03:02:26

标签: r

这里的第一个问题,也是R的新问题。

我有一个根据研究表列表创建数据框的循环。我可以很好地阅读所有的CSV,但我想得到这个领域"主题"并添加变量" study"在现场之前。我的麻烦在于第二个"分配"但是,我无法让R将新值分配给"主题"。

感谢您的帮助。

study <- 'study10'
studytables <- list('ae', 'subject')
studypath <- 'C:/mypath/'

for(table in studytables) {
  destinframe <- paste(table,study, sep='')
  file <- paste(studypath, table, '.CSV', sep='' )
  assign(destinframe, read.csv(file)) # create all dataframes 
  assign(destinframe['Subject'], rep('testing', nrow(get(destinframe))))
}

1 个答案:

答案 0 :(得分:0)

使用assign这样的确不是一个好主意。正如您所看到的,当您尝试将列添加到data.frame时,它无法正常工作。在进行分配之前最好添加列。所以替换

assign(destinframe, read.csv(file))
assign(destinframe['Subject'], rep('testing', nrow(get(destinframe))))

dd <- read.csv(file)
dd$Subject <- paste(study, dd$Subject)
assign(destinframe, dd)