其R中的名字传递参数的函数

问题描述:

我有2个数据帧:

a=c("aaaa","aaaaa", "aaaaaaaa")
b=c(3,5,6)
sample1=data.frame(a,b)

a=c("bb","bbbb","bbbbbbb")
b=c(4,6,54)
sample2=data.frame(a,b)

我想通过样品环路,并通过这些dataframes列某些功能如NCH​​AR(SAMPLE1 $ B)

I want to loop through the samples and pass the columns from these dataframes to some functions e.g. nchar(sample1$b)

所以使用什么应该在for循环做到这一点?下面的code不工作...对不起它的工作,但如长度SAMPLE1 $ B字符串印刷

So using what should go in the for loop to do this? The code below does not work... sorry it does work but the length of e.g. "sample1$b" string is printed

for(i in 1:2) {

   cat(nchar(eval(paste("sample",i,"$b"))))

}

感谢

像MrFlick建议,你应该保存相关dataframes在一个列表:

Like suggested by MrFlick, you should store the related dataframes in a list:

samples <- list(sample1, sample2)

这可以让你避免它的名字指的是每个数据帧:

This allows you to avoid referring to each dataframe by its name:

lapply(samples, function(smp) nchar(smp$b))

如果你真的想使用独立的变量(你不应该!),你可以使用 GET 通过构建它的名字返回对象:

If you really want to use separate variables (you shouldn't!) you can use get to return the object by constructing its name:

for (i in 1:2) print(nchar(get(paste0("sample", i))$b))