在R语言中修改因子水平:合并年龄水平为指定三类
Hey there! Let's sort out how to re-code your demo$age factor levels. You've got 7 detailed age groups and want to collapse them into just three: Total, 18 to 24 years old, and 25 plus. Here are two straightforward methods to get this done:
Method 1: Use forcats (Tidyverse Approach – Clean & Intuitive)
The fct_collapse() function from the forcats package is made for merging factor levels. It lets you map old levels directly to new ones in a readable way.
First, load the package if you haven’t already:
library(forcats)
Option A: Assign observations to core groups, add Total as a placeholder
If Total is meant to be a summary placeholder (not assigned to individual observations), use this:
# Collapse existing levels into your two core age groups demo$age <- fct_collapse( demo$age, "18 to 24 years old" = "18 to 24 years old", # Keep this group unchanged "25 plus" = c( # Merge all 25+ groups into one "25 to 34 years old", "35 to 44 years old", "45 to 54 years old", "55 to 64 years old", "65 to 74 years old", "75 years old or older" ) ) # Add "Total" to the factor levels (even if no observations fall into it yet) demo$age <- factor(demo$age, levels = c("Total", "18 to 24 years old", "25 plus"))
Option B: Map all observations to Total (for summary grouping)
If you want a Total category that includes every observation (e.g., for cross-group summaries), you can map all original levels to it:
demo$age <- fct_collapse( demo$age, "18 to 24 years old" = "18 to 24 years old", "25 plus" = c("25 to 34 years old", "35 to 44 years old", "45 to 54 years old", "55 to 64 years old", "65 to 74 years old", "75 years old or older"), "Total" = levels(demo$age) ) # Reorder levels to match your desired sequence demo$age <- fct_relevel(demo$age, "Total", "18 to 24 years old", "25 plus")
Method 2: Base R Approach (No Extra Packages Needed)
If you prefer sticking to base R, you have a couple of simple options:
Option 1: Use ifelse() to re-code values
# Re-code each observation to either 18-24 or 25+ demo$age <- ifelse( demo$age == "18 to 24 years old", "18 to 24 years old", "25 plus" ) # Convert back to a factor and add the "Total" level demo$age <- factor(demo$age, levels = c("Total", "18 to 24 years old", "25 plus"))
Option 2: Directly modify factor levels
# Rename all non-18-24 levels to "25 plus" levels(demo$age)[levels(demo$age) != "18 to 24 years old"] <- "25 plus" # Add "Total" to the factor levels demo$age <- factor(demo$age, levels = c("Total", levels(demo$age)))
After running either method, you can verify the new levels with levels(demo$age) – you’ll see exactly the three categories you wanted!
内容的提问来源于stack exchange,提问作者SNT

