Remove columns with zero values from a dataframe

Try also

SelectVar[, !apply(SelectVar == 0, 2, all)]

This was taken from here:

Delete all columns with 0 from matrix


One option since dplyr 1.0.0 could be:

df %>%
 select(where(~ any(. != 0)))

     a    b    d    e    g    h    q
1 Dxa8 Dxa8 Dxa8 Dxa8 Dxa8 Dxa8 Dxc8
2 Dxb8 Dxc8 Dxe8 Dxi8 tneg tpos Dxi8

A dplyr friendly solution:

SelectVar %>% select_if(colSums(.) != 0)


You almost have it. Put those two together:

 SelectVar[, colSums(SelectVar != 0) > 0]

This works because the factor columns are evaluated as numerics that are >= 1.

Tags:

R

Dataframe