【问题标题】:R: function parameters inheritanceR:函数参数继承
【发布时间】:2015-01-08 15:23:46
【问题描述】:

所以我有以下代码:

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

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

【问题讨论】:

    标签: r function inheritance


    【解决方案1】:

    您想使用省略号吗(请参阅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)
    
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多