是否有任何方法使用來自dplyr
包的鏈接序列代碼運算符%>%
添加屬性?在dplyr包中以鏈接方式添加屬性
> library(dplyr)
> iris %>%
+ attr("date") = Sys.Date()
Error in iris %>% attr("date") = Sys.Date() :
could not find function "%>%<-"
>
感謝您的回覆。
是否有任何方法使用來自dplyr
包的鏈接序列代碼運算符%>%
添加屬性?在dplyr包中以鏈接方式添加屬性
> library(dplyr)
> iris %>%
+ attr("date") = Sys.Date()
Error in iris %>% attr("date") = Sys.Date() :
could not find function "%>%<-"
>
感謝您的回覆。
你也可以考慮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"
你可以這樣來做:
R> tmp <- iris %>% `attr<-`("date", Sys.Date())
R> attr(tmp,"date")
[1] "2014-09-04"
這依賴於一個事實,即呼籲:
attr(x, "foo") <- "bar"
等效於調用:
x <- `attr<-`(x, "foo", "bar")
太棒了!非常感謝你。那開啓了我的眼睛。 – 2014-09-04 10:33:32
最簡單的辦法 - 如果屬性名稱是已知的 - 是成爲structure
功能:
library(dplyr)
iris <-
iris %>%
structure(date=Sys.Date())
attr(iris,"date") # "2017-02-24"
因爲當屬性名稱是不知道時間提前,@朱巴的解決方案似乎是最好的選擇。
謝謝。很好的解決方案,而不是太古老。 – 2014-09-04 11:23:32