Created
February 20, 2026 13:33
-
-
Save DavisVaughan/f132a9269c77a6f256090bb761726e5e to your computer and use it in GitHub Desktop.
recode-values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| library(dplyr) | |
| likert <- tibble( | |
| score = c(1, 2, 3, 4, 5, 2, 3, 1, 4) | |
| ) | |
| # Typical `case_when()` solution | |
| likert |> | |
| mutate( | |
| category = case_when( | |
| score == 1 ~ "Strongly disagree", | |
| score == 2 ~ "Disagree", | |
| score == 3 ~ "Neutral", | |
| score == 4 ~ "Agree", | |
| score == 5 ~ "Strongly agree" | |
| ) | |
| ) | |
| # `recode_values()` removes a lot of repetition and lets you focus on the mapping | |
| likert |> | |
| mutate( | |
| category = score |> | |
| recode_values( | |
| 1 ~ "Strongly disagree", | |
| 2 ~ "Disagree", | |
| 3 ~ "Neutral", | |
| 4 ~ "Agree", | |
| 5 ~ "Strongly agree" | |
| ) | |
| ) | |
| # Often you don't really want to inline the | |
| # lookup table in the `recode_values()` call | |
| # lookup <- readr::read_csv("lookup.csv") | |
| lookup <- tribble( | |
| ~from , ~to , | |
| 1 , "Strongly disagree" , | |
| 2 , "Disagree" , | |
| 3 , "Neutral" , | |
| 4 , "Agree" , | |
| 5 , "Strongly agree" , | |
| ) | |
| likert |> | |
| mutate(category = recode_values(score, from = lookup$from, to = lookup$to)) | |
| # For added safety, use `unmatched = "error"` if you think you've covered all | |
| # the cases! | |
| likert |> | |
| mutate( | |
| category = score |> | |
| recode_values(from = lookup$from, to = lookup$to, unmatched = "error") | |
| ) | |
| likert <- likert |> add_row(score = 0) | |
| likert |> | |
| mutate( | |
| category = score |> | |
| recode_values(from = lookup$from, to = lookup$to, unmatched = "error") | |
| ) | |
| likert[10, ] |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Rendered