其R中的名字传递参数的函数 [英] Passing arguments to a function by their names in R

查看:219
本文介绍了其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))

这篇关于其R中的名字传递参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆