Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose a function from a tibble of function names, and pipe to it

Tags:

r

magrittr

Let's say I have a tibble (or data frame, whatever) with a list of function names. Let's say, something like:

functions <- tibble(c("log()", "log10()", "sqrt()"))

I want to be able to pipe a data set to one of these functions, chosen by index. For example, I might want to do something like:

data %>% functions[[1]]

But I can't seem to get it to work. I'm very new to pipes, but I am pretty sure this is easy, even if can't get it to work with !! etc.

Thanks in advance.

like image 597
Mooks Avatar asked Mar 23 '18 16:03

Mooks


1 Answers

1) match.fun Use match.fun to turn a string into a function. The dot, ., is optional.

functions <- c("log", "log10", "sqrt")
10 %>% match.fun(functions[2])(.)
## [1] 1

1a) This could also be written as:

10 %>% (match.fun(functions[2]))
## [1] 1

1b) or

10 %>% (functions[2] %>% match.fun)
## [1] 1

2) do.call do.call would also work:

10 %>% { do.call(functions[2], list(.)) }
## [1] 1

3) call/eval Generally eval is frowned upon but it does form another alternative:

10 %>% call(functions[2], .) %>% eval
## [1] 1
like image 116
G. Grothendieck Avatar answered Oct 08 '22 17:10

G. Grothendieck