
Copy attributes from one object to another
copy_attributes.Rd
This function copies over any additional attributes from `source`
into `target`. Any attributes already present in `target` would be
left untouched. This function is useful after manipulating the data
from the *_data
preparation functions to ensure any attributes
necessary for creating the plot aren't lost.
Examples
## 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))
#> $names
#> [1] "Var1" "Var2"
#>
#> $class
#> [1] "data.frame"
#>
#> $row.names
#> [1] 1 2 3 4 5 6 7 8 9 10
#>
print(attributes(b))
#> $names
#> [1] "Var3" "Var4"
#>
#> $class
#> [1] "data.frame"
#>
#> $row.names
#> [1] 1 2 3 4 5 6 7 8 9 10
#>
#> $attr1
#> [1] "Lorem"
#>
#> $attr2
#> [1] "ipsum"
#>
## Copy over attributes of `b` into `a`
print(copy_attributes(target = a, source = b))
#> Var1 Var2
#> 1 0.54460339 0.8570836
#> 2 0.27859715 0.3848097
#> 3 0.44670247 0.5279170
#> 4 0.37151118 0.6006375
#> 5 0.02806097 0.2613714
#> 6 0.46598719 0.2900502
#> 7 0.39003139 0.4800752
#> 8 0.02006522 0.9200055
#> 9 0.37697093 0.4007202
#> 10 0.55991284 0.2131727
## 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)
#> $names
#> [1] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
#>
#> $row.names
#> [1] 1 2 3 4 5 6 7 8 9 10
#>
#> $class
#> [1] "data.frame"
#>
#> $attr1
#> [1] "Lorem"
#>
#> $attr2
#> [1] "ipsum"
#>
## Grouping can drop attributes we set
iris_sub %>%
group_by(Species) %>%
summarise(mean(Sepal.Length)) %>%
attributes()
#> $class
#> [1] "tbl_df" "tbl" "data.frame"
#>
#> $row.names
#> [1] 1
#>
#> $names
#> [1] "Species" "mean(Sepal.Length)"
#>
## 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()
#> $class
#> [1] "tbl_df" "tbl" "data.frame"
#>
#> $row.names
#> [1] 1
#>
#> $names
#> [1] "Species" "mean(Sepal.Length)"
#>
#> $attr1
#> [1] "Lorem"
#>
#> $attr2
#> [1] "ipsum"
#>