在mutate_at中使用case_when [英] Using case_when within mutate_at

查看:118
本文介绍了在mutate_at中使用case_when的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆