I want to drop a column from a data.frame. But when I do, an attribute of the data.frame is lost, which I don't want. First the setup:
d <- data.frame(a = 1, b = 2, c = 3)
attr(d, "test_attribute") <- "something"
d2 <- d
d
#> a b c
#> 1 1 2 3
The test
attribute is present:
attributes(d2) # contains $test_attribute [1] "something"
Now I want to remove the second column - but most ways destroy that attribute:
attributes(d2[, -2]) # it's gone
attributes(dplyr::select(d2, -2)) # it's gone
I found one way to preserve it:
d3 <- d2
d3[2] <- NULL
attributes(d3)
Why does the test_attribute
get dropped in the first two cases, but not when using this last method?
?Extract
describes this behavior.
Subsetting (except by an empty index) will drop all attributes except names, dim and dimnames.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With