简体   繁体   中英

Passing arguments to a function by their names in R

I have 2 data frames:

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)

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 eg "sample1$b" string is printed

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 :

> 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(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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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