gpt4 book ai didi

r - 将select_if与变量名称和类型条件一起使用

转载 作者:行者123 更新时间:2023-12-04 09:36:59 25 4
gpt4 key购买 nike

有关在多种情况下使用dplyr的select_if的文章很多。但是,以任何方式,同时选择is.factor和变量名对我来说都无效。

最终,我想在df / tibble中选择所有因素,并按名称排除某些变量。

例:

df <- tibble(A = factor(c(0,1,0,1)), 
B = factor(c("Yes","No","Yes","No")),
C = c(1,2,3,4))


各种尝试:

尝试1

df %>%
select_if(function(col) is.factor(col) & !str_detect(names(col), "A"))

Error in selected[[i]] <- .p(.tbl[[tibble_vars[[i]]]], ...) : replacement has length zero


尝试2

df %>%
select_if(function(col) is.factor(col) & negate(str_detect(names(col)), "A"))

Error: Can't convert a logical vector to function Call `rlang::last_error()` to see a backtrace


尝试3

df %>%
select_if(function(col) is.factor(col) && !str_detect(names(col), "A"))

Error: Only strings can be converted to symbols Call `rlang::last_error()` to see a backtrace


尝试4

df %>%
select_if(is.factor(.) && !str_detect(names(.), "A"))

Error in tbl_if_vars(.tbl, .predicate, caller_env(), .include_group_vars = TRUE) : length(.p) == length(tibble_vars) is not TRUE


同时,各个条件都可以正常工作:

> df %>%
+ select_if(is.factor)
# A tibble: 4 x 2
A B
<fct> <fct>
1 0 Yes
2 1 No
3 0 Yes
4 1 No

> df %>%
+ select_if(!str_detect(names(.), "A"))
# A tibble: 4 x 2
B c
<fct> <dbl>
1 Yes 1
2 No 2
3 Yes 3
4 No 4


问题可能出在这里:

df %>%
select_if(function(col) !str_detect(names(col), "A"))

Error in selected[[i]] <- .p(.tbl[[tibble_vars[[i]]]], ...) : replacement has length zero


但是,我几乎不知道如何解决此问题。

最佳答案

也许我缺少了一些东西,但是有什么原因您不能执行以下操作:

df <- tibble(A = factor(c(0,1,0,1)), 
B = factor(c("Yes","No","Yes","No")),
C = c(1,2,3,4))


df %>% select_if(function(col) is.factor(col)) %>% select_if(!str_detect(names(.), "A"))

# A tibble: 4 x 1
B
<fct>
1 Yes
2 No
3 Yes
4 No

关于r - 将select_if与变量名称和类型条件一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53837537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com