在mutate_at中使用case_when [英] Using case_when within mutate_at
问题描述
我想在mutate_at
中使用case_when
,如以下示例所示:
I would like to use case_when
within mutate_at
, as in the following example:
mtcars %>%
mutate_at(.vars = vars(vs, am),
.funs = funs(case_when(
. %in% c(1,0,9) ~ TRUE
. %in% c(2,20,200) ~ FALSE
TRUE ~ as.character(.)
)))
在funs()
调用中使用 . =
的
替代版本也不起作用.
alternative version using . =
in funs()
call also does not work.
mtcars %>%
mutate_at(.vars = vars(vs, am),
.funs = funs(. = case_when(
. %in% c(1, 0, 9) ~ TRUE
. %in% c(2, 20, 200) ~ FALSE
TRUE ~ as.character(.)
)))
所需结果
mtcars %>%
mutate_at(.vars = vars(vs, am),
.funs = funs(ifelse(. %in% c(1, 0, 9), TRUE, FALSE)))
FALSE
可以替换为第二个ifelse()
调用,为简洁起见,我没有将其包括在内.
FALSE
could be replaced with second ifelse()
call, which I didn't include for brevity.
推荐答案
我们需要,
来分隔每种情况.另外,如果我们将最后一个选项保留为character
,则TRUE/FALSE
也应为字符.不混合类型
We need ,
to separate each case. Also, if we are keeping the last option as character
, then the TRUE/FALSE
should be character as well. No mixing of types
mtcars %>%
mutate_at(.vars = vars(vs, am),
.funs = funs(. = case_when(
. %in% c(1, 0, 9) ~ TRUE,
. %in% c(2, 20, 200) ~ FALSE,
TRUE ~ TRUE
)))
如果我们需要制作character
类,并且在两种情况中的任何一种都不正确的情况下,也需要将该列作为字符返回,则可能是
If we need to make character
class and also to return the column as character if either of the two cases are not correct, perhaps
mtcars %>%
mutate_at(.vars = vars(vs, am),
.funs = funs(. = case_when(
. %in% c(1, 0, 9) ~ "Yes",
. %in% c(2, 20, 200) ~ "No",
TRUE ~ as.character(.)
)))
这篇关于在mutate_at中使用case_when的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!