2016-05-09 42 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