Filtering out multiple columns in R

后端 未结 6 1572
难免孤独
难免孤独 2021-01-03 16:06

Supposing a data set with several rows and columns with some columns being 0 (I mean all values in the column are 0\'s). How one can filter out those columns? I have tried w

6条回答
  •  醉酒成梦
    2021-01-03 16:49

    Just another way using lapply as it is a data.frame. apply internally converts data.frame to a matrix I believe.

    df[!unlist(lapply(df, function(x) all(x==0)))]
    

    Or in your case:

    df[, 1:99][!unlist(lapply(df[, 1:99], function(x) all(x==0)))]
    

    Edit: Another way using colSums. The trick is to use it after checking for 0.

    df[!colSums(df == 0) == nrow(df)]
    

    If you know which columns are numeric (say, 1:99), then replace df with:

    df[,1:99][!colSums(df[,1:99] == 0) == nrow(df)]
    

提交回复
热议问题