R:函数参数继承

R: function parameters inheritance

所以我有以下代码:

library(semPLS)
data(ECSImobi)

#exponent vector for transformation of the dataset
#model of type plsm
#data 
#returns a list of models with length of exponent vector
#list items are of class sempls
CalcModels <- function(exponent,model,data){

  #initialize result as list
  result <- vector("list")

  #estimate models with different distances
  for(i in seq_along(exponent)){
    result[[i]] <- sempls(model=model, data = data^exponent[i])
  }

  return(result)

}

#calculate ecsi models with exponent 0.1, 0.2, ..., 2.0
ecsiModels <- CalcModels(c(1:20/10),ECSImobi,mobi)

sempls() 函数还有许多其他参数。有什么方法可以将它们提供给 CalcModels 函数,这样我就可以使用 sempls 函数的附加参数 wscheme="pw" 调用 CalcModels 函数。我可以将它们全部写在两个函数的参数中,但我认为必须有一种更聪明的方法,我错过了。

所以我想要这样的东西:

library(semPLS)
data(ECSImobi)

#exponent vector for transformation of the dataset
#model of type plsm
#data 
#returns a list of models with length of exponent vector
#list items are of class sempls
CalcModels <- function(exponent,model,data,wscheme){

  #initialize result as list
  result <- vector("list")

  #estimate models with different distances
  for(i in seq_along(exponent)){
    result[[i]] <- sempls(model=model, data = data^exponent[i],wscheme=wscheme)
  }

  return(result)

}

#calculate ecsi models with exponent 0.1, 0.2, ..., 2.0
ecsiModels <- CalcModels(c(1:20/10),ECSImobi,mobi,"pw")

但不是在两个函数中写入每个参数,而是在不覆盖函数的情况下对参数进行某种继承。

您想使用省略号吗(有关详细信息,请参阅 here)?这是将参数传递给另一个函数的非常有用的技术。您需要做的就是将 ... 添加到函数的定义中:

CalcModels <- function(exponent,model,data,...){

  #initialize result as list
  result <- vector("list")

  #estimate models with different distances
  for(i in seq_along(exponent)){
    result[[i]] <- sempls(model=model, data = data^exponent[i],...)
  }

  return(result)

}

省略号可以传递任意数量的参数。