2013-09-21 78 views
8

標題不是超級描述性的,因爲問題比我能想到的合理標題更長。從函數內抓取對象名稱

我想擁有一個函數,可以從其他函數抓取對象名稱,這些函數可以用作另一個函數中的參數。這裏有一個準系統嘗試:

grab <- function(x) { 
    as.character(substitute(x)) 
} 

FUN <- function(foo, bar = grab(foo)) { 
    bar 
} 

FUN(mtcars) 

在這裏,我的想FUN返回字符串「mtcars」,但它返回「富」。如何做一個抓取功能,這樣做(我想這樣做,因爲我要用這個作爲默認的txt/csv等文件。這是一個便利設置。

這裏有一些不成功的嘗試但我想有一個通用的抓圖功能):

FUN2 <- function(foo, bar = as.character(substitute(bar))) { 
    bar 
} 

FUN2(mtcars) 

#================== 

FUN3 <- function(foo, bar) { 
    if(missing(bar)) bar <- foo 
    as.character(substitute(bar)) 
} 

FUN3(mtcars) 

現實生活上下的例子:

real_example <- function(obj, file = grab(obj)) { 
    write.csv(obj, file = sprintf("%s.csv", file)) 
} 
+0

隨意編輯或編輯標題,使其更清晰。 –

+0

這個問題看起來非常相似:http://stackoverflow.com/questions/5754367/using-substitute-to-get-argument-name-with – Frank

+0

@Frank你有沒有得到任何這些反應的工作? –

回答

6

你可以嘗試sys.call獲得訪問父通話:

## "which" is the number of the argument of interest 
grab <- function(which) { 
    ## which + 1, because [1] == name of function/call 
    ## and arguments are 2:n 
    as.character(sys.call(-1L)[which+1L]) 
} 

FUN <- function(foo, bar = grab(1L)) { 
    bar 
} 

FUN(mtcars) 
# "mtcars" 
+0

這是我正在尋找的行爲。如果其他人有更好的選擇,我會阻止檢查作爲答案(即有人指出有問題)。 –

+0

+1。是的,正如泰勒所說,如果這樣做沒有問題(而不是通過名稱「mtcars」和使用「get」),我也可以使用它。 – Frank

6

這個怎麼樣?

grab <- function(x) as.character(x[["foo"]]) 
FUN <- function(foo, bar=grab(match.call())) { bar } 

FUN(mtcars) 
# [1] "mtcars" 
+0

這也適用。 +1 –