R: 函数参数继承

4

所以我有以下代码:

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")

但是,不要在两个函数中都写每个参数,而是通过某种继承参数的方式,而不会覆盖函数。
1个回答

4

您是否想使用省略号(详见此处了解更多信息)?这是一种非常有用的技术,可以将参数传递给另一个函数。您只需要在函数定义中添加...即可:

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)

}

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接