2016-09-14 79 views
0

在使用...提供的參數列表中簡單的功能,有可能是該功能查找名來自調用傳遞的對象的環境?如果是這樣,怎麼樣?R:獲得在'傳遞的參數名稱...`

這出現在問題printing matrices and vectors side by side的上下文中,但可能更一般。

在這種情況下,參數...也可以包含字符串,但不需要名稱。這裏是我的MWE,我嘗試使用deparse(substitute()),但無濟於事。

test_names <- function(...) { 
    # get arguments 
    args <- list(...) 
    chars <- sapply(args, is.character) 
    names <- sapply(args, function(x) if(is.character(x)) " " else deparse(substitute(x))) 
    names 
} 

測試:

A = matrix(c(0.5, 1, 3, 0.75, 2.8, 4), nrow = 2) 
x = c(0.5, 3.7, 2.3) 
y = c(0.7, -1.2) 
b = A %*% x - y 

> test_names(A, " * ", x, " - ", y, " = ", b) 
[1] "X[[i]]" " "  "X[[i]]" " "  "X[[i]]" " "  "X[[i]]" 
> 

我期望這個輸出是長度爲7的特徵向量:

[1] "A" " " "x" " " "y" " " "b" 

令人驚訝這裏,結果是所有X[[i]],當有在任何地方都沒有提到X

繼@羅蘭的答案,這似乎做什麼,我想:

test_names2 <- function(...) { 
    argnames <- sys.call() 
    unlist(lapply(argnames[-1], as.character)) 
} 

> test_names2(A, " * ", x, " - ", y, " = ", b) 
[1] "A" " * " "x" " - " "y" " = " "b" 
+0

你得到那些從lapply。它不保留列表名稱。 – Roland

+0

編輯顯示所需的輸出 – user101089

回答

1

使用sys.call

test_names <- function(...) { 
    argnames <- sys.call() 
    paste(lapply(argnames[-1], as.character), collapse = "") 
} 
#[1] "A * x - y = b" 
0

隨着電子郵件列表描述(here)或者sys.call作爲羅蘭說或match.call能用於此。

相較於Roland的解決方案,與match.call的解決方案看起來像

f = function(...){ 
    return(match.call()) 
} 

d = f(x = 1, b = 5) 
d 
#f(x = 1, b = 5) 
as.list(d[-1]) 
#$x 
#[1] 1 
# 
#$b 
#[1] 5 

所以有點像這樣使用它,因爲第一個元素是函數本身的名稱。

f = function(...){ 
    return(as.list(match.call())[-1]) 
} 

他們是相似的,但help page說:

sys.call()類似於[到match.call()],但不擴大 參數名稱;

所以這裏有一個區別。