library(dplyr)
data(survey_data)
# Collapse a 5-point scale to 3 categories (inline labels)
data <- rec(survey_data, trust_government,
rules = "1:2=1 [Low]; 3=2 [Medium]; 4:5=3 [High]")
# Reverse a scale (with suffix to keep original)
data <- rec(survey_data, trust_government, trust_media,
rules = "rev", suffix = "_r")
# Dichotomize at the median
data <- rec(survey_data, age, rules = "dicho", suffix = "_d")
# Set missing value codes to NA
data <- rec(survey_data, starts_with("trust"),
rules = "-9=NA; -8=NA; else=copy")
# Replace NA with 0
data <- rec(survey_data, trust_government,
rules = "NA=0; else=copy")
# Quartile split
data <- rec(survey_data, age, rules = "quart", suffix = "_q")
# Use inside mutate()
survey_data <- survey_data %>%
mutate(
trust_gov_3 = rec(trust_government,
rules = "1:2=1 [Low]; 3=2 [Medium]; 4:5=3 [High]"),
age_q = rec(age, rules = "quart")
)
Run the code above in your browser using DataLab