## Simple example
a <- data.frame(Var1 = runif(1:10), Var2 = runif(1:10))
b <- data.frame(Var3 = runif(1:10), Var4 = runif(1:10))
attr(b, "attr1") <- "Lorem"
attr(b, "attr2") <- "ipsum"
print(attributes(a))
print(attributes(b))
## Copy over attributes of `b` into `a`
print(copy_attributes(target = a, source = b))
## Note the attributes already present in `a` are left untouched
## Can also be used in the dplyr pipeline
library(dplyr)
iris_sub <- iris[1:10, ]
attr(iris_sub, "attr1") <- "Lorem"
attr(iris_sub, "attr2") <- "ipsum"
attributes(iris_sub)
## Grouping can drop attributes we set
iris_sub %>%
group_by(Species) %>%
summarise(mean(Sepal.Length)) %>%
attributes()
## Use copy_attributes with `iris_sub` object as source
## to add the attributes again
iris_sub %>%
group_by(Species) %>%
summarise(mean(Sepal.Length)) %>%
copy_attributes(source = iris_sub) %>%
attributes()
Run the code above in your browser using DataLab