Hi there, it seems you have your variables mixed up - you want to define IMD_quintile using the values in IMD_group. Your code seems to want to do the opposite. Also, you need to define the tribble prior to working on it. Lastly, since you want an integer, I removed the quotes in the recoded values. This creates a dbl vector, so if you need integers you would force that conversion too. How does this look?
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(tibble)
my_tribble = tibble::tribble(
~ID, ~IMD_group,
1L, "A1 (LQ)",
2L, "A2",
3L, "A3",
4L, "A1 (LQ)",
5L, "A5 (HD)",
6L, "A4",
7L, "A1",
8L, "A4",
9L, "A5 (HD)",
10L, "A2"
)
IMD_one <- c("A1 (LQ)")
IMD_two <- c("A2")
IMD_three <- c("A3")
IMD_four <- c("A4")
IMD_five <- c("A5 (HD)")
tribble1 <- my_tribble %>%
mutate(
IMD_quintile = case_when(
IMD_group %in% IMD_one ~ 2,
IMD_group %in% IMD_two ~ 3,
IMD_group %in% IMD_three ~ 4,
IMD_group %in% IMD_four ~ 5
),
IMD_quintile = as.integer(IMD_quintile)
)
print(tribble1)
#> # A tibble: 10 × 3
#> ID IMD_group IMD_quintile
#> <int> <chr> <int>
#> 1 1 A1 (LQ) 2
#> 2 2 A2 3
#> 3 3 A3 4
#> 4 4 A1 (LQ) 2
#> 5 5 A5 (HD) NA
#> 6 6 A4 5
#> 7 7 A1 NA
#> 8 8 A4 5
#> 9 9 A5 (HD) NA
#> 10 10 A2 3
Created on 2021-11-29 by the reprex package (v2.0.1)