我想从 data.frame 中删除一列。但是当我这样做时,data.frame 的一个属性丢失了,这是我不想要的。首先设置:
d <- data.frame(a = 1, b = 2, c = 3)
attr(d, "test_attribute") <- "something"
d2 <- d
d
#> a b c
#> 1 1 2 3
test
属性存在:attributes(d2) # contains $test_attribute [1] "something"
现在我想删除第二列 - 但大多数方法都会破坏该属性:attributes(d2[, -2]) # it's gone
attributes(dplyr::select(d2, -2)) # it's gone
我找到了一种保存它的方法:d3 <- d2
d3[2] <- NULL
attributes(d3)
为什么test_attribute
在前两种情况下被丢弃,但在使用最后一种方法时不会被丢弃?
最佳答案
?Extract
描述了这种行为。
Subsetting (except by an empty index) will drop all attributes except names, dim and dimnames.
关于r - 从 data.frame 中删除一列会导致不必要的属性丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65452476/