2016-05-09 39 views
2

假设我有两个函数使用三个点构造作为它们的参数。如何将列表()转换为R中的省略号?

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

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

下面是一个示例代码:

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试过,但我有一个错误消息:

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

这是因为第二个函数不能将name参数识别为elli的单独参数psis的论点。

预期的结果是:

这是名称:测试

这些参数:1,4,9

回答

5

仅举参数:

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