Using case_when within mutate_at

若如初见. 提交于 2019-12-03 20:16:09

问题


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

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

Desired results

mtcars %>% 
  mutate_at(.vars = vars(vs, am),
         .funs = funs(ifelse(. %in% c(1, 0, 9), TRUE, FALSE)))

FALSE could be replaced with second ifelse() call, which I didn't include for brevity.


回答1:


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


来源:https://stackoverflow.com/questions/47887950/using-case-when-within-mutate-at

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