【问题标题】:R: get columns that only have value 0R:获取只有值 0 的列
【发布时间】:2020-03-30 02:11:59
【问题描述】:

示例代码:

df:

#                        a                       b                       c
# 1 -0.0010616345688829504  -4.1135727372109387e-05 -0.0001814242939304348

只有 1 行 3000+ 列。

我想知道如何只选择带有 0 的列(其中有我已经确认查看数据。)

期待这样的事情:

res:

#   d                        e                      f
# 1 0                        0                      0

【问题讨论】:

    标签: r apply


    【解决方案1】:

    Filter 的选项来自base R

    Filter(function(x) all(x == 0), df)
    #   d e f
    #1 0 0 0
    

    或者dplyr

    library(dplyr)
    df %>%
       select_if(~ all(. == 0))
    #  d e f
    #1 0 0 0
    

    数据

    df <- structure(list(a = -0.00106163456888295, b = -4.11357273721094e-05, 
        c = -0.000181424293930435, d = 0, e = 0, f = 0), class = "data.frame", row.names = c(NA, 
    -1L))
    

    【讨论】:

      【解决方案2】:

      可以说是最简单的解决方案(使用@arg0naut91 的数据):

      df[, df==0]
        d e f
      1 0 0 0
      

      【讨论】:

      • 为我返回undefined columns selected
      • 你在用@arg0naut91的df吗?
      【解决方案3】:

      如果只有一行,你可以否定列(如0 == FALSE):

      res <- df[, !df]
      

      或者检查colSums在哪里0

      res <- df[, colSums(df) == 0]
      

      输出:

        d e f
      1 0 0 0
      

      数据:

      df <- structure(list(a = -0.00106163456888295, b = -4.11357273721094e-05, 
          c = -0.000181424293930435, d = 0, e = 0, f = 0), class = "data.frame", row.names = c(NA, 
      -1L))
      

      基准测试显示@akrun 的Filter 是迄今为止最快的(没有包括dplyr 变体,因为它是迄今为止最慢的):

      Unit: milliseconds
          expr     min       lq     mean   median       uq      max neval
         which 25.1935 26.95415 29.42942 28.00300 31.34740 181.5487  1000
            == 14.2807 15.25200 16.84471 15.73310 16.92505 182.6126  1000
        Filter  1.6767  1.80705  2.02523  1.90270  1.99135   7.5026  1000
       colSums 11.0489 11.85425 12.83663 12.26115 13.04670  23.9469  1000
             ! 14.2278 15.07710 16.55270 15.55400 16.76835 187.0145  1000
      

      基准代码:

      set.seed(3234)
      
      ncols <- 3000
      df <- as.data.frame(matrix(rpois(ncols, 0.5), ncol = ncols))
      
      bench <- microbenchmark::microbenchmark(
      
        which = df[, which(df[1, ] == 0)],
        `==` = df[, df == 0],
        Filter = Filter(function(x) all(x == 0), df),
        colSums = df[, colSums(df) == 0],
        `!` = df[, !df],
        times = 1000
      
      )
      

      【讨论】:

        【解决方案4】:
        df[,which(df[1,]==0)] 
        

        应该做的工作。

        【讨论】:

          猜你喜欢
          • 2020-07-10
          • 2021-09-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-08
          相关资源
          最近更新 更多