This answer警告which
中存在一些恐怖行为。具体来说,如果您获取任何数据框,例如说df <- data.frame(x=1:5, y=2:6)
,然后尝试使用计算结果为which(FALSE)
(即integer(0)
)的子集对其进行子集化,则将删除数据集中的每一列。为什么是这样?为什么删除与integer(0)
对应的所有列会删除所有内容?删除任何内容都不会破坏一切。
示例:
>df <- data.frame(x=1:5, y=2:6)
>df
x y
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6
>df <- df[,-which(FALSE)]
>df
data frame with 0 columns and 5 rows
identical(integer(0), -integer(0))
# [1] TRUE
所以,实际上您什么都不是[[selecting,而不是什么都不删除。
如果不希望删除,则可以使用大的负整数,例如最大的可能。
df[, -.Machine$integer.max] # x y # 1 1 2 # 2 2 3 # 3 3 4 # 4 4 5 # 5 5 6