英文:
mutate_if multiple conditions along with case_when in R
问题
我想对那些是因子且只有2个水平的列应用case_when
函数,而且它们的名称不包含"kiwi"。
这不起作用。我可以通过其他较长的方法得到我想要的结果,但我想知道是否有一种高效的方法来做到这一点。
library(dplyr)
library(stringr)
df <- data.frame(orange = factor(c(1,1,0,1,0)),
apple = factor(c("x", "x", "y", "y", "x")),
peach = 1:5,
kiwi = factor(c("a", "a", "b", "b", "c")))
df2 <- df %>%
mutate_if(~ is.factor(.) & nlevels(.) == 2 & !str_detect(names(.), "kiwi"),
~ case_when(.x == 0 ~ "No",
.x == 1 ~ "Yes",
TRUE ~ as.character(.x)))
英文:
I want to apply the case_when function over those columns who are factors and have only 2 levels and whose names do not contain "kiwi".
This does not work. I can get what I want with other longer approaches but I was wondering if there is any way to do this is an efficient way.
librare(dplyr)
library(stringr)
df <- data.frame(orange = factor(c(1,1,0,1,0)),
apple = factor(c("x", "x", "y", "y", "x")),
peach = 1:5,
kiwi = factor(c("a", "a", "b", "b", "c")))
df2 <- df %>%
mutate_if((~ is.factor(.) & nlevels(.) == 2 & str_detect(names(.), "kiwi", negate = TRUE)),
~ dplyr::case_when(.x == 0, "No",
.x == 1 ~ "Yes",
TRUE ~ .x))
答案1
得分: 3
从对一组变量进行操作中提到
作用域动词(
_if
,_at
,_all
)已被使用现有动词中的pick()
或across()
取代。有关详情,请参阅vignette("colwise")
。
使用 across()
,您可以使用<tidy-select> 语法来保留或删除列:
- 因子列:
where(is.factor)
- 仅有 2 个水平的列:
where(~ nlevels(.x) == 2)
- 列名不包含 "kiwi" 的列:
!contains("kiwi")
df %>%
mutate(across(where(~ is.factor(.x) & nlevels(.x) == 2) & !contains("kiwi"),
~ case_when(.x == 0 ~ "No",
.x == 1 ~ "Yes",
TRUE ~ .x)))
英文:
From Operate on a selection of variables, it said
> Scoped verbs (_if
, _at
, _all
) have been superseded by the use of pick()
or across()
in an existing verb. See vignette("colwise")
for details.
With across()
, you can use the <tidy-select> syntax to keep or drop columns:
- columns which are factors:
where(is.factor)
- have only 2 levels:
where(~ nlevels(.x) == 2)
- columns whose names do not contain "kiwi":
!contains("kiwi")
df %>%
mutate(across(where(~ is.factor(.x) & nlevels(.x) == 2) & !contains("kiwi"),
~ case_when(.x == 0 ~ "No",
.x == 1 ~ "Yes",
TRUE ~ .x)))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论