Select a function from the name of the function names, and for it, the handset

Say I have (or a data frame) and a list of function names. Say something like:

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

I want to be able to connect a data set to one of these functions, selected by index. For example, I could do something like:

 data %>% functions[[1]] 

But I can’t make it work. I am very new to pipes, but I'm sure it is easy, even if you can’t get it to work! etc.

Thanks in advance.

+5
source share
3 answers

You can do it:

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

there is no reason to put them in the header, and if you do, you will need functions[[1]][1] , as @ Aaghaz-Hussain mentions.

 seq(10) %>% get(functions[1])() # [1] 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379 1.7917595 1.9459101 2.0794415 2.1972246 2.3025851 

get will extract the function definition from its name as a string, after which it is a simple channel, except that you must be sure that () are explicit as seq(10) %>% get(functions[[1]]) , it will be interpreted as seq(10) %>% get(.,functions[[1]])

+3
source

1) match.fun Use match.fun to turn a string into a function. The point . not required.

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

1a) It can 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 will also work:

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

3) call / eval In general, eval disapproving, but it creates another alternative:

 10 %>% call(functions[2], .) %>% eval ## [1] 1 
+6
source

In addition to the answers already received, it is worth noting that you can store almost everything in R lists, even in functions. So this also works:

 funs <- list(log, log10, sqrt) f <- funs[[1]] 2 %>% f 
+4
source

Source: https://habr.com/ru/post/1276044/


All Articles