2014-09-04 22 views
2

是否有任何方法使用來自dplyr包的鏈接序列代碼運算符%>%添加屬性?在dplyr包中以鏈接方式添加屬性

> library(dplyr) 
> iris %>% 
+ attr("date") = Sys.Date() 
Error in iris %>% attr("date") = Sys.Date() : 
    could not find function "%>%<-" 
> 

感謝您的回覆。

回答

5

你也可以考慮setattr from「data.table」:

library(dplyr) 
library(data.table) 
names(attributes(iris)) 
# [1] "names"  "row.names" "class" 

iris %>% setattr(., "date", Sys.Date()) 
names(attributes(iris)) 
# [1] "names"  "row.names" "class"  "date" 
attributes(I2)$date 
# [1] "2014-09-04" 

當然,這樣的事情實際上不需要鏈接。你可以只是做:

setattr(iris, "date", Sys.Date()) 

這允許您設置的屬性沒有問題複製對象:

> v1 <- 1:4 
> v2 <- 1:4 
> tracemem(v1) 
[1] "<0x0000000011cffa38>" 
> attr(v1, "foo") <- "bar" 
tracemem[0x0000000011cffa38 -> 0x0000000011d740f8]: 
> tracemem(v2) 
[1] "<0x0000000011db2da0>" 
> setattr(v2, "foo", "bar") 
> attributes(v2) 
$foo 
[1] "bar" 
+0

謝謝。很好的解決方案,而不是太古老。 – 2014-09-04 11:23:32

6

你可以這樣來做:

R> tmp <- iris %>% `attr<-`("date", Sys.Date()) 

R> attr(tmp,"date") 
[1] "2014-09-04" 

這依賴於一個事實,即呼籲:

attr(x, "foo") <- "bar" 

等效於調用:

x <- `attr<-`(x, "foo", "bar") 
+0

太棒了!非常感謝你。那開啓了我的眼睛。 – 2014-09-04 10:33:32

0

最簡單的辦法 - 如果屬性名稱是已知的 - 是成爲structure功能:

library(dplyr) 

iris <- 
    iris %>% 
    structure(date=Sys.Date()) 

attr(iris,"date") # "2017-02-24" 

因爲當屬性名稱是不知道時間提前,@朱巴的解決方案似乎是最好的選擇。

相關問題