Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apply a list of functions to a single argument in R

Tags:

r

Hi I am trying to apply a list of functions to a single argument in R. For example,

flist <- list(F,G,H) #F,G,H are function objects

and say I want as a result a list or vector (F(x),G(x),H(x)) where x is a scalar number. Do you know how i can achieve that?

like image 300
NickD1 Avatar asked Jan 09 '23 06:01

NickD1


1 Answers

The most efficient way (it seems) to achieve this would be using a single lapply (instead of 3 different functions), such as

flist <- list(mean, unique, max) # Example functions list
MyScalar <- 1 # Some scalar
lapply(flist, function(f) f(MyScalar))
# [[1]]
# [1] 1
# 
# [[2]]
# [1] 1
# 
# [[3]]
# [1] 1

Though, if all the functions give the same size/class result, you could improve it even more using vapply

vapply(flist, function(x) x(MyScalar), FUN.VALUE = double(1))
## [1] 1 1 1
like image 168
David Arenburg Avatar answered Jan 12 '23 09:01

David Arenburg