Created
June 23, 2025 05:15
-
-
Save LibbyHeeren/8da6367ba371ecc6cc9006a7e2409011 to your computer and use it in GitHub Desktop.
Recoding a column using a named list as a dictionary in R
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
| # Load packages | |
| library(dplyr) | |
| # Create a named list mapping likert numbers to full responses | |
| likert_mapping <- list( | |
| "1" = "Strongly disagree", | |
| "2" = "Disagree", | |
| "3" = "Neutral", | |
| "4" = "Agree", | |
| "5" = "Strongly agree" | |
| ) | |
| # Create fake data | |
| fake_survey <- | |
| tibble( | |
| question = c("pr1", "pt3", "qr6", "cc2", "pr2", "qr8", "pt5"), | |
| score = c("1", "2", "1", "2", "5", "8", "4") | |
| ) | |
| # Use recode() to replace numeric values based on likert response mapping | |
| # Unmatched values will default to NA (character NA) | |
| fake_survey_replaced <- | |
| fake_survey |> | |
| mutate( | |
| response = recode(score, !!!likert_mapping, .default = NA_character_) | |
| ) | |
| # `!!!` acts as if you've typed out likert_mapping's elements one by one | |
| # so it's the same as typing all this: | |
| mutate( | |
| response = recode( | |
| score, | |
| "1" = "Strongly disagree", | |
| "2" = "Disagree", | |
| "3" = "Neutral", | |
| "4" = "Agree", | |
| "5" = "Strongly agree", | |
| .default = NA_character_ | |
| ) | |
| ) | |
| # Did that work? | |
| fake_survey_replaced | |
| # Yes! | |
| # A tibble: 7 × 3 | |
| # question score response | |
| # <chr> <chr> <chr> | |
| # 1 pr1 1 Strongly disagree | |
| # 2 pt3 2 Disagree | |
| # 3 qr6 1 Strongly disagree | |
| # 4 cc2 2 Disagree | |
| # 5 pr2 5 Strongly agree | |
| # 6 qr8 8 NA | |
| # 7 pt5 4 Agree |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment