Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropping a column from a data.frame causes unwanted loss of an attribute

Tags:

dataframe

r

attr

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?

like image 516
Sam Firke Avatar asked Dec 25 '20 23:12

Sam Firke


1 Answers

?Extract describes this behavior.

Subsetting (except by an empty index) will drop all attributes except names, dim and dimnames.

like image 51
Ronak Shah Avatar answered Nov 14 '22 20:11

Ronak Shah