2015-12-02 25 views
0

爲什麼get()結合paste()適用於數據幀,但不適用於數據幀內的列?我怎麼能使它工作?R:使用get()和paste()返回列

ab<-12 
get(paste("a","b",sep="")) 
# gives: [1] 12 

ab<-data.frame(a=1:3,b=3:5) 
ab$a 
#gives: [1] 1 2 3 

get(paste("a","b",sep="")) 
# gives the whole dataframe 

get(paste("ab$","a",sep="")) 
# gives: Error in get(paste("ab$", "a", sep = "")) : object 'ab$a' not found 
+0

嚴肅的問題:你爲什麼要這麼做? – Heroka

+0

你可以用'eval(parse(text = ...))'來做到這一點,但是R讓這種尷尬和困難的程度應該是你使用'get'的整個方法可能並不理想的信號。 – joran

+0

只是因爲'$'是一個函數,'get'不會評估傳遞給它的對象,所以試着用'c':'get(「c(1,2,3)」)' –

回答

1

dataframes中的列不是第一類對象。他們的「名字」實際上是列表提取的索引值。儘管由於存在names函數而導致可理解的混淆,但它們在R對象列表中並不是真實的R名稱,即未加引號的標記或符號。請參閱?is.symbol幫助頁面。 get函數接受一個字符值,然後在工作空間中查找它並將其返回以供進一步處理。

> ab<-data.frame(a=1:3,b=3:5) 
> ab$a 
[1] 1 2 3 
> get(paste("a","b",sep="")) 
    a b 
1 1 3 
2 2 4 
3 3 5 
> 
> # and this would be the way to get the 'a' column of the ab object 

get(paste("ab",sep=""))[['a']] 

如果有一個命名對象target一個值 「a」 tehn你也可以這樣做:

target <- "a" 
get(paste("ab",sep=""))[[target]] # notice no quotes around target 
            # because `target` is a _real_ R name 
+0

非常全面的解釋!謝謝! – joaoal

2

它不起作用,因爲get()解釋它是指一個名爲"ab$a"對象(不是指一份名爲"ab"對象的"a"元素)傳遞的字符串。這可能是查看含義的最佳方法:

ab<-data.frame(a=1:3,b=3:5) 
`ab$a` <- letters[1:3] 
get("ab$a") 
# [1] "a" "b" "c" 
+0

完美。謝謝! – joaoal