从for循环中按名称访问变量

时间:2016-05-31 09:51:21

标签: r loops eval

我为列表(category.levels = c("Art","Music",...)的每个类别名称创建了多个数据框 - 每个类别级别有一个数据框。数据帧称为Data_Art, Data_Music等。

我现在尝试在for循环中循环时访问这些数据帧,并使用其他一般数据帧为每个数据帧执行合并。我的问题是我所有的试验得到变量所代表的真实变量都失败了...... 例如,我尝试了以下内容:

for (cat in category.levels)
{
  curr.dataset = eval(parse(text=paste("Data",cat,sep='_')))
  merged.data = merge(curr.dataset,other_data,by=c("user_id"))
 ... 
}

我还试图用get()但仍然 - 在我的所有试验中,最终curr.datasetstring变量而不是字符串代表的变量...(我看到了环境查看器它是一个字符串,我收到merge操作的错误消息。如果我在循环外尝试相同的一切都很好。在循环中使用eval/get是否有问题?

1 个答案:

答案 0 :(得分:0)

您确定您的Data_对象是数据框吗?您的代码适合我:

<强> test_eval.R

user_id <- c(1001,1004,1007)
favorite_artist <- c("Monet","Van Gogh", "Picasso")
Data_Art <- data.frame( user_id, favorite_artist )

user_id <- c(1002,1005,1008)
favorite_composer <- c("Bach","Beethoven", "Bernstein")
Data_Music <- data.frame( user_id, favorite_composer )

user_id <- c(1003,1006,1009)
favorite_scientist <- c("Einstein","Newton", "Galen")
Data_Science <- data.frame( user_id, favorite_scientist )

user_id <- c(1001:1009)
favorite_philospher <- c("Aristotle", "Plato", "Kant", "Nietzsche", "Descartes", "Marx", "Buddha", "Confucius", "Averroes")
Data_Philosophy <- data.frame( user_id, favorite_philospher )

user_id <- c(1001:1009)
name <-c("Aaron","Betty","Charles","Dolly","Edgar","Felicia","Grover","Helen","Isaac")
other_data <- data.frame( user_id, name )

category.levels = c("Art","Music","Science","Philosophy")
for ( cat in category.levels) {
    dfname = paste("Data",cat,sep='_')
    print(dfname)
    curr.dataset = eval(parse(text=dfname))
    merged.data = merge(curr.dataset, other_data, by=c("user_id"))
    print(merged.data)
}

<强>输出

source('test_eval.R')
[1] "Data_Art"
  user_id favorite_artist   name
1    1001           Monet  Aaron
2    1004        Van Gogh  Dolly
3    1007         Picasso Grover
[1] "Data_Music"
  user_id favorite_composer  name
1    1002              Bach Betty
2    1005         Beethoven Edgar
3    1008         Bernstein Helen
[1] "Data_Science"
  user_id favorite_scientist    name
1    1003           Einstein Charles
2    1006             Newton Felicia
3    1009              Galen   Isaac
[1] "Data_Philosophy"
  user_id favorite_philospher    name
1    1001           Aristotle   Aaron
2    1002               Plato   Betty
3    1003                Kant Charles
4    1004           Nietzsche   Dolly
5    1005           Descartes   Edgar
6    1006                Marx Felicia
7    1007              Buddha  Grover
8    1008           Confucius   Helen
9    1009            Averroes   Isaac