根据其元素而不是其名称选择列

aio*_*orr 2 r dplyr

假设我想选择所有包含1.

test.dat <- tibble(
  name = c("A","B","C"),
  alert_A = c(1,1,1),
  alert_B = c(1,1,0),
  alert_C = c(1,0,1),
  alert_D = c(1,0,0),
  alert_E = c(0,0,0)
)

> test.dat
# A tibble: 3 x 6
  name  alert_A alert_B alert_C alert_D alert_E
  <chr>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>
1 A           1       1       1       1       0
2 B           1       1       0       0       0
3 C           1       0       1       0       0
> test.want
# A tibble: 3 x 5
  name  alert_A alert_B alert_C alert_D
  <chr>   <dbl>   <dbl>   <dbl>   <dbl>
1 A           1       1       1       1
2 B           1       1       0       0
3 C           1       0       1       0
Run Code Online (Sandbox Code Playgroud)

在 tidyselect 中,contains()基于列名称上的字符串模式进行匹配。我想要的是根据列是否包含数值进行匹配。

我的猜测是is.element在 select 中使用,但我怎样才能做到这一点?

test.answer <- test.dat %>%
  select(name,~is.element(1,.))
#error
Run Code Online (Sandbox Code Playgroud)

akr*_*run 5

我们可以使用where类型检查来返回字符列 ( is.character) 或 ( |) 如果它是数字类型 ( is.numeric),然后还检查any值是否为 1

library(dplyr)
test.dat %>% 
   select(where(~ is.character(.)||(is.numeric(.) && any(. == 1))))
Run Code Online (Sandbox Code Playgroud)

-输出

# A tibble: 3 x 5
#  name  alert_A alert_B alert_C alert_D
#  <chr>   <dbl>   <dbl>   <dbl>   <dbl>
#1 A           1       1       1       1
#2 B           1       1       0       0
#3 C           1       0       1       0
Run Code Online (Sandbox Code Playgroud)