从所有值为NA,NULL或空的数据框中删除列

这个问题在这里已经有了答案:

  • R:删除字符变量的多个空列6个答案

  • 我们可以使用Filter

    Filter(function(x) !(all(x=="")), df)
    #   Var1 Var3
    #1  2R+   52
    #2  2R+  169
    #3  2R+   83
    #4  2R+   98
    #5  2R+   NA
    #6  2R+  111
    #7  2R+   94
    #8  2R+  116
    #9  2R+   86
    

    注意:如果某个特定列的所有元素都是NA,它也应该可以工作

    df$Var3 <- NA
    Filter(function(x) !(all(x=="")), df)
    #   Var1
    #1  2R+
    #2  2R+
    #3  2R+
    #4  2R+
    #5  2R+
    #6  2R+
    #7  2R+
    #8  2R+
    #9  2R+
    

    更新

    根据更新的数据集,如果我们需要删除只有0个值的列,则将代码更改为

    Filter(function(x) !(all(x==""|x==0)), df2)
    #    VAR1 VAR3 VAR4 VAR7
    #1  2R+   52 1.05   30
    #2  2R+  169 1.02   40
    #3  2R+   83   NA   40
    #4  2R+   98 1.16   40
    #5  2R+  154 1.11   40
    #6  2R+  111   NA   15
    

    数据

    df2 <- structure(list(VAR1 = c("2R+", "2R+", "2R+", "2R+", "2R+", "2R+"
    ), VAR2 = c("", "", "", "", "", ""), VAR3 = c(52L, 169L, 83L, 
    98L, 154L, 111L), VAR4 = c(1.05, 1.02, NA, 1.16, 1.11, NA), VAR5 = c(0L, 
    0L, 0L, 0L, 0L, 0L), VAR6 = c(0L, 0L, 0L, 0L, 0L, 0L), VAR7 = c(30L, 
    40L, 40L, 40L, 40L, 15L)), .Names = c("VAR1", "VAR2", "VAR3", 
    "VAR4", "VAR5", "VAR6", "VAR7"), row.names = c("1", "2", "3", 
    "4", "5", "6"), class = "data.frame")
    
    链接地址: http://www.djcxy.com/p/96267.html

    上一篇: Remove columns from dataframe where ALL values are NA, NULL or empty

    下一篇: Unable to reset R rownames, rownames(df) returns NULL