Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R中的动态函数名_R - Fatal编程技术网

R中的动态函数名

R中的动态函数名,r,R,我需要做的是在循环中使用R中的which.min和which.max函数 我可以使用if语句(即if find\u max\u value==TRUE然后which.max(…)或者which.min(…) 但我想知道是否有一种方法可以真正使函数名动态化。 例如: min_or_max = 'max' special_text = paste('which.',min_or_max,sep='') special_text(df_results$point) 有没有办法让上面的文字起作用?也

我需要做的是在循环中使用R中的
which.min
which.max
函数

我可以使用
if
语句(即
if find\u max\u value==TRUE然后which.max(…)或者which.min(…)

但我想知道是否有一种方法可以真正使函数名动态化。 例如:

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

有没有办法让上面的文字起作用?

也许
do.call
是你想要的:

minu或max='max'
特殊文本=粘贴('which',最小值或最大值,sep='')
do.呼叫(特殊文本,列表(mtcars$cyl))
#> [1] 5

也许
去做。打电话是你要找的:

minu或max='max'
特殊文本=粘贴('which',最小值或最大值,sep='')
do.呼叫(特殊文本,列表(mtcars$cyl))
#> [1] 5

我们可以从
purrr

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

我们可以使用
invoke
from
purrr

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

如果您需要从可能的函数列表中进行选择,最好将它们存储在列表中

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

funs如果需要从可能的函数列表中进行选择,最好将它们存储在列表中

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

funs您也可以使用
match.fun

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

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

您还可以使用
match.fun

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

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

是的,正是我需要的!是的,正是我需要的!您可以将函数或对象名称粘贴在一起,但这会使事情变得非常脆弱,难以调试。通常最好直接将函数作为参数传递,或使用控制/流代码(if语句等)处理案例。您可以将函数或对象名称粘贴在一起,但这会使事情变得非常脆弱,难以调试。通常最好直接将函数作为参数传递,或使用控制/流代码(if语句等)处理案例。为什么使用双括号?双括号将从列表中返回函数。使用单括号将子集列表(返回列表)。为什么使用双括号?双括号将从列表中返回函数。使用单括号将子集列表(返回列表)。