I have a dataframe such as :
g1 g2 g3 g4 g5
2 0 1 0 1
2 1 1 0 1
2 1 1 2 1
and I would like to remove each column that have at least one 2 in its values.
and get a new df :
g2 g3 g5
0 1 1
1 1 1
1 1 1
Thanks for your help.
We can use colSums
here:
df <- data.frame(g1=c(2,2,2), g2=c(0,1,1), g3=c(1,1,1), g4=c(0,0,2), g5=c(1,1,1))
df[, !colSums(df==2)]
g2 g3 g5
1 0 1 1
2 1 1 1
3 1 1 1
The idea is to include all rows from the original data frame, but only include those columns which never have a value of 2. In that case, the call to colSums()
would be zero, which is logically equivalent to false
in R.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With