如何在R语言DataFrame中按天数范围新增分组标签列
Hey there! For your task of adding a grouping column to your DataFrame based on the Days values, there are two super practical approaches you can use—one with the dplyr package (super readable for complex logic) and another with base R's built-in cut function (no extra packages needed). Let's break them down:
Approach 1: Use dplyr::case_when (Recommended for Readability)
First, make sure you have the dplyr package installed (if not, run install.packages("dplyr") first). Then you can write your conditions in a clear, straightforward way:
# Initialize your data Name = c("A", "B", "C", "D", "E") Days = c(3,4,5,16,26) df = data.frame(Name, Days) # Load dplyr library(dplyr) # Add the grouping column df <- df %>% mutate(Group = case_when( Days < 7 ~ "1 Week", Days >= 7 & Days <= 14 ~ "1-2 Weeks", Days > 14 & Days <= 30 ~ "1 Month", TRUE ~ "Other" # Catch-all for values outside your specified ranges (optional) ))
After running this, your df will have the new Group column, which looks like this:
Name Days Group 1 A 3 1 Week 2 B 4 1 Week 3 C 5 1 Week 4 D 16 1 Month 5 E 26 1 Month
Approach 2: Use Base R's cut Function
If you don't want to load an external package, base R's cut function works perfectly for binning numeric values into groups. Just define your breakpoints and corresponding labels:
# Initialize your data Name = c("A", "B", "C", "D", "E") Days = c(3,4,5,16,26) df = data.frame(Name, Days) # Add the grouping column df$Group <- cut( x = df$Days, breaks = c(-Inf, 7, 14, 30, Inf), labels = c("1 Week", "1-2 Weeks", "1 Month", "Other"), include.lowest = TRUE # Ensures values equal to the lower breakpoint get grouped correctly )
This will give you exactly the same result as the dplyr method, and it's great for quick, lightweight tasks without package dependencies.
Quick Notes
- Both methods handle edge cases properly:
Days=7andDays=14go to "1-2 Weeks", whileDays=30lands in "1 Month" - The "Other" label is optional—feel free to remove that part if you don't need to handle values outside your target ranges
内容的提问来源于stack exchange,提问作者realbeast91

