简体   繁体   English

通过R中的名称将参数传递给函数

[英]Passing arguments to a function by their names in R

I have 2 data frames: 我有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)

I want to loop through the samples and pass the columns from these dataframes to some functions eg nchar(sample1$b) 我想遍历样本并将这些数据帧中的列传递给某些函数,例如nchar(sample1 $ b)

So using what should go in the for loop to do this? 因此,使用应在for循环中执行的操作是什么? The code below does not work... sorry it does work but the length of eg "sample1$b" string is printed 下面的代码不起作用...对不起,它起作用了,但是打印了例如“ sample1 $ b”字符​​串的长度

for(i in 1:2) {

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

}

Thanks 谢谢

First, you fix the first problem, which is that your data frames aren't all in a single list by collecting them via mget : 首先,解决第一个问题,即通过mget收集数据帧,使它们不在单个列表中:

> l <- mget(x = paste0("sample",1:2))
> l
$sample1
         a b
1     aaaa 3
2    aaaaa 5
3 aaaaaaaa 6

$sample2
        a  b
1      bb  4
2    bbbb  6
3 bbbbbbb 54

Once that problem has been remedied, you can simply use lapply on the resulting list: 解决该问题后,您只需在结果列表中使用lapply即可:

> lapply(l,function(x) nchar(x[["b"]]))
$sample1
[1] 1 1 1

$sample2
[1] 1 1 2

Like suggested by MrFlick, you should store the related dataframes in a list: 就像MrFlick所建议的那样,您应该将相关数据框存储在列表中:

samples <- list(sample1, sample2)

This allows you to avoid referring to each dataframe by its name: 这使您避免通过名称来引用每个数据框:

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

If you really want to use separate variables (you shouldn't!) you can use get to return the object by constructing its name: 如果您确实想使用单独的变量(不应该!),则可以使用get来构造对象的名称,以返回该对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM