我需要做的是在一个循环中使用R中的which.min
和which.max
函数。
我可以只使用if
语句(即if find_max_value == TRUE then which.max(…) else which.min(…)
但我想知道是否有一种方法可以真正使函数名动态化。例如:
min_or_max = 'max'
special_text = paste('which.',min_or_max,sep='')
special_text(df_results$point)
有没有办法让上面的文本起作用?
发布于 2020-10-27 22:28:51
如果需要从可能的函数列表中进行选择,最好将它们存储在列表中。例如
funs <- list(max = which.max, min=which.min)
min_or_max = 'max'
funs[[min_or_max]](df_results$point)
这比尝试使用任意字符串作为代码要安全得多。此外,您还可以在尝试运行代码之前验证是否存在正确的值:min_or_max %in% names(funs)
发布于 2020-10-27 22:22:06
我们可以从purrr
使用invoke
library(purrr)
invoke(special_text, list(mtcars$cyl))
#[1] 5
发布于 2020-10-27 21:46:26
也许do.call
就是你要找的东西:
min_or_max = 'max'
special_text = paste('which.',min_or_max,sep='')
do.call(special_text, list(mtcars$cyl))
#> [1] 5
https://stackoverflow.com/questions/64563297
复制相似问题