kwicher
kwicher

Reputation: 2082

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 e.g. 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 e.g. "sample1$b" string is printed

for(i in 1:2) {

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

}

Thanks

Upvotes: 1

Views: 104

Answers (2)

Molx
Molx

Reputation: 6931

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))

Upvotes: 1

joran
joran

Reputation: 173577

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

Upvotes: 1

Related Questions