Using case_when within mutate_at

我们两清 提交于 2019-11-30 15:14:54

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
        )))

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(.)
        ))) 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!