Selecting all columns that have some specific values

Viewed 141

I have a data.frame with more than 50 columns and 10,000 rows I want select those columns that are haveing 0 or 1 in them excluding other values in those columna

sample data.frame is as below:

dummy_df <- data.frame(
                        id=1:4,
                        gender=c(4,1,0,1),
                        height=seq(150, 180,by = 10),
                        smoking=c(3,0,1,0)
                       )

I want to select all those columns with 0 or 1 value and exclude other values like 4 in gender and 3 in smoking and as below

  gender  smoking
    1         0
    0         1
    1         0

but I have 50 columns in actual data frame and I don't know which of them are having 0 or 1

What I'm trying is:

 dummy_df %>% select_if(~ all(  . %in% 0:1))
2 Answers

Is this useful for you?

dummy_df %>% 
  select(- c(id, height)) %>%
  rowwise() %>% 
  filter(any(c_across() == 0)|any(c_across() == 1))
# A tibble: 3 x 2
# Rowwise: 
  gender smoking
   <dbl>   <dbl>
1      1       0
2      0       1
3      1       0

EDIT:

If you don't know in advance which cols contain 0 and/or 1, you can determine that in base R:

temp <- dummy_df[sapply(dummy_df, function(x) any(x == 0|x == 1))]

Now you can filter for rows with 0and/or 1:

temp %>% 
  rowwise() %>% 
  filter(any(c_across() == 0)|any(c_across() == 1))

I think it's more like a case of filter than select:

library(dplyr)


dummy_df %>%
  filter(if_all(c(gender, smoking), ~ .x %in% c(0, 1)))


  id gender height smoking
1  2      1    160       0
2  3      0    170       1
3  4      1    180       0
Related