选择具有某些特定值的所有列

时间:2021-04-30 13:47:54

标签: r

我有一个包含 50 多列和 10,000 行的 data.frame 我想选择那些包含 0 或 1 的列,不包括这些列中的其他值a

示例数据框如下:

mytuple = (('2200', '10:00 PM'), ('2230', '10:30 PM'), ('2300', '11:00 PM'), ('2330', '11:30 PM'), ('0', '12:00 AM'), ('30', '12:30 AM'))

我想选择所有值为 0 或 1 的列,并排除其他值,例如性别为 4,吸烟为 3,如下所示

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)
                       )

但我在实际数据框中有 50 列,我不知道其中哪些是 0 或 1

我正在尝试的是:

  gender  smoking
    1         0
    0         1
    1         0

2 个答案:

答案 0 :(得分:2)

这对你有用吗?

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

编辑

如果您事先不知道哪些列包含 0 和/或 1,您可以在 base R 中确定:

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

现在您可以使用 0 和/或 1 过滤行:

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

答案 1 :(得分:2)

我认为这更像是 filter 而不是 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