Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over function to build list

Tags:

r

plyr

I have a list of functions:

func1 <- function(u)
{
    list(val=u, ref="XX1")
}

func2 <- function(u)
{
    list(val=u*u, ref="XX55")
}

func3 <- function(u)
{
    list(val=u-1, ref="XX3")
}

And i want to get a result like this with u=2:

list(XX55=4, XX3=1, XX1=2)

For the moment I proceed like that:

funcs = c(func1, func2, func3)

temp = llply(funcs, function(f) f(2))
res  = llply(temp, function(u) u$val)
names(res) = llply(temp, function(u) u$ref)
res

But maybe is there a more elegant/concise way to proceed?

like image 374
Colonel Beauvel Avatar asked Mar 25 '26 07:03

Colonel Beauvel


1 Answers

You can use sapply:

sapply(funcs, function(f) {tmp <- f(2); setNames(list(tmp$val), tmp$ref)})
# $XX1
# [1] 1
#
# $XX55
# [1] 341
#
# $XX3
# [1] 11
like image 111
Sven Hohenstein Avatar answered Mar 27 '26 20:03

Sven Hohenstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!