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_Function - Fatal编程技术网

传递本身是参数的R函数的参数

传递本身是参数的R函数的参数,r,function,R,Function,在R中,环境之类的东西总是让我难以置信地困惑。我想这更像是一个参考请求,因为我已经在网站上浏览了一个小时,寻找一个没有用的答案 我有一个简单的R函数,名为target,定义如下 target <- function(x,scale,shape){ s <- scale b <- shape value <- 0.5*(sin(s*x)^b + x + 1) return(value) } 正在评估功能目标。不幸的是,调用返回以下错误

在R中,环境之类的东西总是让我难以置信地困惑。我想这更像是一个参考请求,因为我已经在网站上浏览了一个小时,寻找一个没有用的答案

我有一个简单的R函数,名为
target
,定义如下

target <- function(x,scale,shape){

    s <- scale
    b <- shape

    value <- 0.5*(sin(s*x)^b + x + 1)
    return(value)

}
正在评估功能
目标
。不幸的是,调用返回以下错误

sample <-  AR(n = 10000, f = target, shape = 8, scale = 5)
     Error in fun(z, scale, shape) : object 'shape' not found

sample你非常接近,你只需要利用你的椭圆

NB:
c
未在
AR
中定义,因此我添加了它并给它一个值。
NB2:我不想在函数中使用
c
sample
,因为这些函数本身就是函数,可能会引起一些混乱

AR <- function(n, f, c, ...){
  variates <- NULL

  for(i in 1:n){
    z <- runif(1)
    u <- runif(1)

    if(u < f(z, ...)/c){ ##instead of using shape and scale use the ellipses and R will insert any parameters here which were not defined in the function
      variates[i] <- z
    }else{next}

  }
  variates <- variates[!is.na(variates)]
  return(variates)
}

sample <-  AR(n = 10000, f = target, shape = 8, scale = 5, c = 100)

AR谢谢@emiliman,非常清楚。在命名法上有很好的观点!
AR <- function(n, f, c, ...){
  variates <- NULL

  for(i in 1:n){
    z <- runif(1)
    u <- runif(1)

    if(u < f(z, ...)/c){ ##instead of using shape and scale use the ellipses and R will insert any parameters here which were not defined in the function
      variates[i] <- z
    }else{next}

  }
  variates <- variates[!is.na(variates)]
  return(variates)
}

sample <-  AR(n = 10000, f = target, shape = 8, scale = 5, c = 100)