简体   繁体   中英

Dynamic function names in R

What I need to do is use both the which.min and which.max functions in R in a loop.

I could just use an if statement (ie if find_max_value == TRUE then which.max(…) else which.min(…)

but I was wondering if there is a way to actually make the function name dynamic. For example:

min_or_max =  'max'
special_text = paste('which.',min_or_max,sep='')
special_text(df_results$point)

is there somehow to make the above text work?

We can use invoke from purrr

library(purrr)
invoke(special_text, list(mtcars$cyl))
#[1] 5

If you need to choose from a list of possible functions, better to store them in a list. For example

funs <- list(max = which.max, min=which.min)
min_or_max =  'max'
funs[[min_or_max]](df_results$point)

This is much safer than trying to use arbitrary strings as code. Plus you can validate that a proper value exists before you try to run the code: min_or_max %in% names(funs)

Maybe do.call is what you are looking for:

min_or_max =  'max'
special_text = paste('which.',min_or_max,sep='')
do.call(special_text, list(mtcars$cyl))
#> [1] 5

You can also use match.fun :

match.fun(special_text)(mtcars$mpg)
#[1] 20

#Verifying the results
which.max(mtcars$mpg)
#[1] 20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM