Here are a few examples that will hopefully clarify what's going wrong. Note that I've used the %in%
function to reduce the number of lines of code needed. Also, add TRUE ~ P57_2
in order to ensure non-recoded values keep their original values (rather than being set to missing).
library(tidyverse)
# Fake data
d = tibble(x=c(5, 10, "No", 1, "Yes", "Y", "NS", "NC"))
# The recoded values are set to zero, but all the other values are set
# to missing
d %>%
mutate(x_recode = case_when(x %in% c("No","NS","NC") ~ 0))
#> # A tibble: 8 x 2
#> x x_recode
#> <chr> <dbl>
#> 1 5 NA
#> 2 10 NA
#> 3 No 0
#> 4 1 NA
#> 5 Yes NA
#> 6 Y NA
#> 7 NS 0
#> 8 NC 0
# This errrors out because `case_when` expects all values to have the
# same class (character, numeric, etc.) but here we tried to recode some
# values to numeric while leaving some as their original character values
d %>%
mutate(x_recode = case_when(x %in% c("No","NS","NC") ~ 0,
TRUE ~ x))
#> Error: Problem with `mutate()` input `x_recode`.
#> x must be a double vector, not a character vector.
#> ℹ Input `x_recode` is `case_when(x %in% c("No", "NS", "NC") ~ 0, TRUE ~ x)`.
# This works because we assigned "0", which is character class, so all the
# values are character
d %>%
mutate(x_recode = case_when(x %in% c("No","NS","NC") ~ "0",
TRUE ~ x))
#> # A tibble: 8 x 2
#> x x_recode
#> <chr> <chr>
#> 1 5 5
#> 2 10 10
#> 3 No 0
#> 4 1 1
#> 5 Yes Yes
#> 6 Y Y
#> 7 NS 0
#> 8 NC 0
# Now we've recoded all the character values to numbers, but we're still
# keeping everything as character class
d %>%
mutate(x_recode = case_when(x %in% c("No","NS","NC") ~ "0",
x %in% c("Yes","Y") ~ "1",
TRUE ~ x))
#> # A tibble: 8 x 2
#> x x_recode
#> <chr> <chr>
#> 1 5 5
#> 2 10 10
#> 3 No 0
#> 4 1 1
#> 5 Yes 1
#> 6 Y 1
#> 7 NS 0
#> 8 NC 0
# Finally, change the class to numeric, so that we end up with a column of
# numeric values, rather than character values
d %>%
mutate(x_recode = case_when(x %in% c("No","NS","NC") ~ "0",
x %in% c("Yes","Y") ~ "1",
TRUE ~ x),
x_recode = as.numeric(x_recode))
#> # A tibble: 8 x 2
#> x x_recode
#> <chr> <dbl>
#> 1 5 5
#> 2 10 10
#> 3 No 0
#> 4 1 1
#> 5 Yes 1
#> 6 Y 1
#> 7 NS 0
#> 8 NC 0
Created on 2020-11-13 by the reprex package (v0.3.0)