【问题标题】:How to convert a list() to an ellipsis in R?如何将列表()转换为R中的省略号?
【发布时间】:2016-05-09 14:24:28
【问题描述】:

假设我有两个函数使用三个点结构作为参数。

我想检索第一个函数的省略号并为第二个函数创建一个全新的参数列表。

如何将新创建的列表传递给第二个函数?

这是一个示例代码:

first.function <- function(..., name) {
  argument.list <- list(...)

  new.args <- list()
  for (i in 1:length(argument.list)) {
    new.args[[i]] <- argument.list[[i]]^2
  }
  new.args[[length(new.args) + 1]] <- name

  do.call(second.function, new.args)
}

second.function <- function(..., name) {
  print(paste("This is the name:", name))
  print(paste("These are the arguments:", ...))
}

first.function(1, 2, 3, name = "Test")

我尝试使用 do.call,但出现错误消息:

粘贴错误(“这是名称:”,名称):参数“名称”是 缺失,没有默认值

这是因为第二个函数无法将名称参数识别为与省略号参数分开的参数。

预期结果是:

这是名称:测试

这些是参数:1、4、9

【问题讨论】:

    标签: r


    【解决方案1】:

    只需命名参数:

    first.function <- function(..., name) {
      argument.list <- list(...)
    
      new.args <- lapply(argument.list, `^`, 2) 
      new.args[["name"]] <- name
    
      do.call(second.function, new.args)
    }
    
    first.function(1, 2, 3, name = "Test")
    #[1] "This is the name: Test"
    #[1] "These are the arguments: 1 4 9"
    

    这里是语言定义相关部分的链接:4.3.2 Argument matching

    【讨论】:

      猜你喜欢
      • 2019-04-04
      • 2011-03-25
      • 2023-03-31
      • 1970-01-01
      • 2011-03-09
      • 2012-01-22
      • 2015-12-24
      • 2017-09-21
      • 2019-02-14
      相关资源
      最近更新 更多