假设我想选择所有包含 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
在 tidyselect 中,contains()
根据列的名称 上的字符串模式进行匹配。我想要的是根据某列是否包含数值来匹配。
我的猜测是在 select 中使用 is.element
,但我该如何实现呢?
test.answer <- test.dat %>%
select(name,~is.element(1,.))
#error
最佳答案
我们可以使用 where
检查类型以返回字符列 (is.character
) 或 (|
) 如果它是数字类型 (is.numeric
),然后检查 any
值是否为 1
library(dplyr)
test.dat %>%
select(where(~ is.character(.)||(is.numeric(.) && any(. == 1))))
-输出
# 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
关于r - 根据元素而不是名称选择列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67221161/