-1

What should I do if I want to remove the columns which are contained just the 0 or NA or both values?

mat <- structure(c(0L, 0L, 1L, 0L, 2L, 0L, 0L, 0L, NA, 0L, 0L, 0L, 0L,
0L, 2L, 0L, 0L, NA, 0L, 0L, 0L, 1L, 0L, 0L, NA, 0L, NA, 0L, 0L,
0L, 0L, NA, 0L, 2L, 0L, 0L), .Dim = c(6L, 6L), .Dimnames = list(
c("A05363", "A05370", "A05380", "A05397", "A05400", "A05426"), c("X1.110590170", "X1.110888172", "X1.110906406", "X1.110993854", "X1.110996710", "X1.111144756")))

My output should be like this:

        X1.110590170   X1.110906406   X1.110993854   X1.111144756
A05363             0              0              0              0
A05370             0              0              0             NA
A05380             1              2              0              0
A05397             0              0              1              2
A05400             2              0              0              0
A05426             0             NA              0              0
Ati
  • 55
  • 1
  • 7
  • 2
    I did actually update my answer on your previous question in response to your comment http://stackoverflow.com/questions/31397042/remove-the-columns-with-the-colsums-0/31397062?noredirect=1#comment50812762_31397062 – mathematical.coffee Jul 15 '15 at 03:11
  • 1
    @mathematical.coffee Seems to me you _should_ have the power to close R questions. – IRTFM Jul 15 '15 at 03:38

1 Answers1

1

You can filter out the columns using the apply function along the columns.

You will simply have to use the all function to make sure that all values in the column satisfy the logic: is.na(x) | x == 0.

filter_cols <- apply(mat, 2, function(x) !all(is.na(x) | x == 0))
mat[,filter_cols]
#'         X1.110590170 X1.110906406 X1.110993854 X1.111144756
#'  A05363            0            0            0            0
#'  A05370            0            0            0           NA
#'  A05380            1            2            0            0
#'  A05397            0            0            1            2
#'  A05400            2            0            0            0
#'  A05426            0           NA            0            0
chappers
  • 2,415
  • 14
  • 16