Вы можете достичь желаемого, используя функцию do.call()
, которая используется для запуска функции, хранящейся в переменной / параметре.
Следующий пример иллюстрирует это:
f1 <- function (x){
y = cos(x)-0.80+0.10^2
return (y)
}
f2 <- function (x){
y = -sin(x) + (x/50)
return (y)
}
f3 <- function (x){
y = (x-3)^5
return (y)
}
test_call_function_passed_as_parameter <- function(f, x) {
cat("The value of ", deparse(substitute(f)), "(", x, ") is: ",
do.call(f, list(x)), "\n", sep="") # Note the use of list() to pass the arguments to f()
}
test_call_function_passed_as_parameter(f1, 3)
test_call_function_passed_as_parameter(f1, 5)
test_call_function_passed_as_parameter(f2, 3)
test_call_function_passed_as_parameter(f3, 3)
, который дает следующий вывод:
The value of f1(3) is: -1.779992
The value of f1(5) is: -0.5063378
The value of f2(3) is: -0.08112001
The value of f3(3) is: 0