Search code examples
rcase-when

r dplyr::case_when Error: must be a character vector, not a double vector


I am trying to use dplyr::case_when within dplyr::mutate to replace some values:

data<-data%>%
  mutate(floor = case_when(
    floor_id == 2 ~ "ground_floor",
    floor_id == 3 ~ "mezzanine",
    floor_id == 1 ~ "basement",
    floor_id == 30 ~ "over_10",
    floor==1 ~ 1,
    floor==2 ~ 2,
    floor==3 ~ 3,
    floor==4 ~ 4,
    floor==5 ~ 5,
    floor==6 ~ 6,
    floor==7 ~ 7,
    floor==8 ~ 8,
    floor==9 ~ 9,
    floor==10 ~ 10,
    TRUE ~ as.character(floor)))

I have an error

Error: must be a character vector, not a double vector

I have 2 questions: 1) Does anyone know how to change the code to fix this error? 2) If no cases match, NA is returned that is why I add all these lines like floor==10 ~ 10. Is there any way to make the code less redundant?


Solution

    1. case_when is type-strict meaning you need to return values of same type. For first few cases you are returning values like "ground-floor", "mezzanine" etc whereas later you are returning 1, 2 which are numeric hence you get that error. If you change all your return values to character values like "1", "2" etc then it will work.

    2. Since, you are just returning the floor values you can reduce the code by:

      library(dplyr)
      data<- data%>%
              mutate(floor = case_when(
                     floor_id == 2 ~ "ground_floor",
                     floor_id == 3 ~ "mezzanine",
                     floor_id == 1 ~ "basement",
                     floor_id == 30 ~ "over_10",
                     TRUE ~ as.character(floor)))