[英]Passing a function with parameters as an argument to another function in R
[英]R: Function as argument of another function
我編寫了R函數myplot()
,它在間隔[ myplot()
上繪制了一條與提供的函數FUN
相對應的曲線。
myplot <- function(FUN)
{
curve(FUN(x), xlim = c(-10, 10))
}
例如
myplot(FUN = dnorm)
給
如何向FUN
添加參數? 例如,假設我要用平均值5繪制法線密度。
遵循@akrun的評論,我可以執行以下操作:
myplot <- function(FUN, ...)
{
args <- list(...)
curve(FUN(x, unlist(args)), xlim = c(-10, 10))
}
myplot(dnorm, mean = 5)
但是之后
> myplot(FUN = dnorm)
Error in FUN(x, unlist(args)) :
Argument non numérique pour une fonction mathématique
另外, myplot(FUN = dnorm, mean = 5, sd = 2)
不能給出預期的圖像...
您的原始功能運行良好(但您的原始示例有錯字)
myplot <- function(FUN, ...)
{
curve(FUN(x, ...), xlim = c(-10, 10))
}
myplot(dnorm)
myplot(dnorm, mean = 5)
myplot(dnorm, mean = 5, sd=2)
一切似乎工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.