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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With