2

I have data as follows:

df <- data.frame(A=c(1,2,3), B=c(1,0,1), C=c(0.1, 0.011, 0.3), D=c(0, 0.5, 1))

  A B     C   D
1 1 1 0.100 0.0
2 2 0 0.011 0.5
3 3 1 0.300 1.0

Ho can I remove all binary variables (= B) from this data.frame?

Tom
  • 2,173
  • 1
  • 17
  • 44

3 Answers3

3

You could do

library(dplyr)

df %>% select(!where(~all(.x %in% 0:1)))
  A     C   D
1 1 0.100 0.0
2 2 0.011 0.5
3 3 0.300 1.0
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
3

You can use this:

Filter(function(x) !all(x %in% c(0, 1)), df)

Output:

  A     C   D
1 1 0.100 0.0
2 2 0.011 0.5
3 3 0.300 1.0

Note: you could also add NA to c(0, 1) if needed.

Quinten
  • 35,235
  • 5
  • 20
  • 53
2

Another option for fun, We can also explicity search for each value (as @Allan Cameron mentions), i.e.

df[colSums(df ==1 | df == 0) != nrow(df)]

#  A     C   D
#1 1 0.100 0.0
#2 2 0.011 0.5
#3 3 0.300 1.0
Sotos
  • 51,121
  • 6
  • 32
  • 66