8

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?

kskirpic
  • 155
  • 1
  • 1
  • 7

1 Answers1

15
  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)))
    
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    Proposed solution is not the right one because with this solution all floors from 1 to 10 will be replaced with NA values because as I wrote "If no cases match, NA is returned". – kskirpic May 31 '20 at 06:54
  • 1
    I rechecked, your solution works, it might me I did not use the line TRUE ~ as.character(floor) previous time when I got NA values. Thank you! – kskirpic May 31 '20 at 07:31