【问题标题】:Why does dropping which(FALSE) columns delete all columns?为什么删除 which(FALSE) 列会删除所有列?
【发布时间】:2021-01-21 00:08:49
【问题描述】:

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

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    考虑:

    identical(integer(0), -integer(0))
    # [1] TRUE
    

    所以,实际上你选择什么都没有,而不是什么都删除。

    如果你不想删除什么,你可以使用一个大的负整数,例如尽可能大。

    df[, -.Machine$integer.max]
    #   x y
    # 1 1 2
    # 2 2 3
    # 3 3 4
    # 4 4 5
    # 5 5 6
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-27
      • 2020-01-09
      相关资源
      最近更新 更多