Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop columns by patterns values in R

Tags:

dataframe

r

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.

like image 411
chippycentra Avatar asked Jan 02 '23 05:01

chippycentra


1 Answers

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.

like image 169
Tim Biegeleisen Avatar answered Jan 13 '23 11:01

Tim Biegeleisen