2013-02-13 80 views
-1

我想在data.frame的頂部存儲附加信息並從函數返回它。正如你所看到的 - 額外的數據消失。 例如:從函數中返回一個完整的數據幀R

> d<-data.frame(N1=c(1,2,3),N2=(LETTERS[1:3])) 
> d 
    N1 N2 
1 1 A 
2 2 B 
3 3 C 
> d.x = 3 
> d 
    N1 N2 
1 1 A 
2 2 B 
3 3 C 
> d.x 
[1] 3 
> foo1 <- function() { 
+ d<-data.frame(N1=c(1,2,3),N2=(LETTERS[1:3])) 
+ d.x=3 
+ return(d) 
+ } 
> 
> d1<-foo1() 
> d1 
    N1 N2 
1 1 A 
2 2 B 
3 3 C 
> d1.x 
Error: object 'd1.x' not found 

我看着assign,但由於在函數內部創建的data.frame並恢復我認爲這不是與此有關。 謝謝。

+0

這沒有什麼意義。數據框3應該在數據框d的頂部添加值3?一個新的行?屬性? – joran 2013-02-13 19:39:49

+0

我知道你的意思,但它的作品,這是我需要的。唯一的問題是,當我從函數返回data.frame時,不會返回其他數據。我只需要返回一個包含數據行和元數據的數據結構。 – haki 2013-02-13 19:45:35

+0

您需要對R進行最小限度的介紹。d.x是一個單獨的對象,與x無關。如果你想在d中有一個名爲x的列,那麼你可以將它稱爲d $ x – lebatsnok 2014-01-04 17:43:51

回答

1

您的意見建議你要創建一個名爲屬性(通常的方式附加 「元數據」 的對象在R)「d 0.3" ,並使用foo1來設置一個數據幀該屬性:

d <- data.frame(N1=c(1,2,3),N2=(LETTERS[1:3])) 
foo1 <- function(d, attrib) { 
    attr(d, "d.x") <- attrib 
    return(d) 
    } 
d <- foo1(d, 3) # need to assign value to 'd' since function results are not "global" 
d # note that the default print method for dataframes does not show the attributes 
#--------- 
    N1 N2 
1 1 A 
2 2 B 
3 3 C 
#----- 
attributes(d) 
#----- 

$names 
[1] "N1" "N2" 

$row.names 
[1] 1 2 3 

$class 
[1] "data.frame" 

$d.x 
[1] 3 

?attr?attributes瞭解更多細節。還有一個comments函數。

0

更改此:

d.x=3 

這樣:

d$x=3 
+0

雖然答案是正確的,但解釋需要更改的人是有幫助的。 – 2013-02-13 20:08:37

+0

這可能是OP之後的內容,但我們應該注意到它會創建3列的整列,而不是單個值。 – joran 2013-02-13 20:10:18

相關問題