Adding attributes in chaining way in dplyr package

安稳与你 提交于 2019-12-06 03:31:18

问题


Is there any way to add an attribute using chaining sequence code operator %>% from dplyr package?

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

Thanks for respone.


回答1:


You can also consider 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"

Of course, no chaining is actually required for something like this. You could just do:

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

This allows you to set attributes without copying the objects in question:

> 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"



回答2:


You can do it this way :

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

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

This relies on the fact that calling :

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

is equivalent to calling :

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



回答3:


If the attribute name is known, the simplest solution is to use the structure function:

library(dplyr)

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

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

When the attribute name is not know, @juba's solutions seems to be the best alternative.



来源:https://stackoverflow.com/questions/25662859/adding-attributes-in-chaining-way-in-dplyr-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!