You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言DataFrame中按天数范围新增分组标签列

Add Group Labels to R DataFrame Based on Numeric Ranges

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:

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=7 and Days=14 go to "1-2 Weeks", while Days=30 lands 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 21:02:45