find_value <-function(function_2, x)
{
x<-readline(prompt = "Enter a real number ")
function_2<-readline(prompt="Enter a function")
x<-as.numeric(x)
function_2<-as.function(function_2)
return(function_2(x))
}
該函式應該找到一個實數的數學函式的值
uj5u.com熱心網友回復:
as.function沒有按預期作業。你可以使用get.
find_value <-function(function_2, x) {
x <- readline(prompt = "Enter a real number ")
function_2 <- readline(prompt="Enter a function")
x <- as.numeric(x)
function_2 <- get(function_2, mode = "function")
return(function_2(x))
}
或者match.fun評論中建議的更好的替代方案:
find_value <- function(function_2 = NULL, x = NULL) {
if(is.null(x)) x <- readline(prompt = "Enter a real number ")
if(is.null(function_2)) function_2 <- readline(prompt="Enter a function")
x <- as.numeric(x)
function_2 <- match.fun(function_2)
return(function_2(x))
}
我們可以進一步添加檢查,是否提供了引數,這樣我們就可以在沒有引數的情況下運行函式。在這種情況下,它會要求我們輸入,或者我們提供 args 并且該函式將只回傳計算值。
find_value <-function(function_2 = NULL, x = NULL) {
if(is.null(x)) x <- readline(prompt = "Enter a real number ")
if(is.null(function_2)) function_2 <- readline(prompt="Enter a function")
x <- as.numeric(x)
function_2 <- match.fun(function_2)
return(function_2(x))
}
find_value("sqrt", 4)
#> [1] 2
由reprex 包(v0.3.0)于 2022-01-22 創建
我們也可以使用rlang::as_functionwhich 支持類似 purrr 的 lambda 函式:
find_value <-function(function_2 = NULL, x = NULL) {
if(is.null(x)) x <- readline(prompt = "Enter a real number ")
if(is.null(function_2)) function_2 <- readline(prompt="Enter a function")
x <- as.numeric(x)
function_2 <- rlang::as_function(function_2)
return(function_2(x))
}
find_value(~ .x^2, 4)
#> [1] 16
由reprex 包(v0.3.0)于 2022-01-22 創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/420267.html
標籤:
