简体   繁体   中英

How to delete a column based on a condition in R

I have following data frame :

user_id product_1 product_2 product_3 product_3 product_4
1          1        2           0        4       5
2          0        0           0        1       3
3          4        6           0        8       4
4          2        4           0        2       2
5          4        4           0        0       0

generally how can i exclude columns where sum(column)==0 , and how can i do it using dplyr package?

If you don't have to use dplyr package, you can also do this in base :

df[colSums(df) != 0]

  user_id product_1 product_2 product_3.1 product_4
1       1         1         2           4         5
2       2         0         0           1         3
3       3         4         6           8         4
4       4         2         4           2         2
5       5         4         4           0         0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM