带点传递函数参数

时间:2019-03-25 19:53:49

标签: r

我正在尝试编写一个函数来计算R中的样本量。

该函数使用几个较小的函数。我想使用点将参数传递给较小的函数。到目前为止,这是我的功能:

log_reg_var<-function(p){
  if(p<=0|p>=1) stop('p must be between 0 and 1')
  var<-1/(p*(1-p))
  return(var)
}

samplesize<-function(method_name, beta, sigma_x, mult_cor, power= 0.8,fpr = 0.05,...){

  if(method_name=='linear regression'){
    var_func <- lin_reg_var
  }
  else if(method_name=='logistic regression'){
    var_func <- log_reg_var
  }
  else if(method_name=='cox regression'){
    var_func <- cox_reg_var
  }
  else if(method_name=='poisson regression'){
    var_func <- pois_reg_var
  }
  else{
    stop('method_name not recognized. method_name accepts one of: "linear regression",
         "logistic regression","cox regression", or "poisson regression"')
  }

  top = (qnorm(1-fpr/2) + qnorm(power))^2
  bottom = (beta*sigma_x)^2*(1-mult_cor)

  n = (top/bottom)*var_func(...)

  return(ceiling(n))

}

我应该能够做

samplesize(method_name = 'logreg',1,1,0,p=0.5)
>>>32

但是相反,我抛出了以下错误:

Error in var_func(...) : argument "p" is missing, with no default

很显然我将p穿过圆点时出了点问题,但是我不确定这是怎么回事。

我这是什么问题?

1 个答案:

答案 0 :(得分:0)

您需要添加附加参数p作为参数,并且需要将其传递到log_reg_var()函数中。您还必须注意其他一些语法:

log_reg_var<-function(p){
  if(p<=0|p>=1) stop('p must be between 0 and 1')
  var<-1/(p*(1-p))
  return(var)
}

# specify that you pass a parameter `p`
samplesize<-function(method_name, beta, sigma_x, mult_cor, power= 0.8,fpr = 0.05, p, ...){

# Initialize `var_func` to a NULL value
var_func = NULL

  if(method_name=='linear regression'){
    var_func <- lin_reg_var(p)
  }
  else if(method_name=='logistic regression'){
    # pass parameter `p` into log_reg_var since there is no default
    var_func <- log_reg_var(p)
  }
  else if(method_name=='cox regression'){
    var_func <- cox_reg_var(p)
  }
  else if(method_name=='poisson regression'){
    var_func <- pois_reg_var(p)
  }
  else{
    stop('method_name not recognized. method_name accepts one of: "linear regression",
     "logistic regression","cox regression", or "poisson regression"')
  }

  top = (qnorm(1-fpr/2) + qnorm(power))^2
  bottom = (beta*sigma_x)^2*(1-mult_cor)

  n = (top/bottom)*var_func

  return(ceiling(n))

}

> samplesize(method_name ='logistic regression', 1, 1, 0, p=0.5)
[1] 32