r - 从 data.frame 中删除一列会导致不必要的属性丢失

标签 r dataframe attr

我想从 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/

相关文章:

r - 在 R 中使用 gstat 进行克里金法时,多慢算太慢

python - 使用 Python 将具有不同 UTC 基准​​的时间戳列转换为当前 UTC

python - 根据另一个 DataFrame 的列名子集 DataFrame

grails - grails单选按钮组是否没有其他值的tabindex?

ember.js - Emberjs - 模型中的属性应该全部以小写字母开头吗?

r - 在 R 中选择空单元格

R:如何将列表保存到 csv 中?

r - 如何不成比例地分割 y 轴以更好地在图中显示数据

python - 遍历 pandas 中的组以提取顶部

javascript - 属性 "src"左侧图像包含零