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

R语言中按组批量求和多变量的高效实现方法

Flexible Grouped Summation for Prefix-Matched Variables

Hey there! I totally get the frustration of hardcoding variable names when the count (n) can change—let's fix that with dynamic, scalable approaches that work no matter how many vol_* columns you have.

Option 1: Using dplyr (Tidyverse)

This is my go-to for readability and flexibility. We'll use starts_with() to target all columns starting with your prefix (vol_), then summarize each by group:

library(dplyr)

# Replace "vol_" with your actual variable prefix
data2 <- df %>%
  group_by(group) %>%
  summarise(across(starts_with("vol_"), sum, na.rm = TRUE))
  • starts_with("vol_") automatically picks all columns that start with your prefix—perfect even if n grows or shrinks.
  • across() applies the sum function (with na.rm = TRUE) to every matched column in one go.

Option 2: Base R (No External Libraries)

If you prefer sticking to base R, we can dynamically generate the list of columns and build the aggregation formula:

# Step 1: Identify columns matching the pattern (prefix + numbers)
target_cols <- grep("^vol_\\d+$", names(df), value = TRUE)
# The regex ^vol_\\d+$ means: starts with "vol_", followed by one or more digits, ends there

# Step 2: Build the formula dynamically
agg_formula <- as.formula(paste(paste(target_cols, collapse = ", "), "~ group"))

# Step 3: Run the aggregation
data2 <- aggregate(agg_formula, data = df, sum, na.rm = TRUE)
  • The regex ensures we only select columns like vol_1, vol_2—not any other columns that might have "vol_" in the name (like vol_total).
  • By building the formula dynamically, we avoid hardcoding each variable name, so it adapts automatically when n changes.

Why This Is Better Than Your Original Code

Your original approach works but requires updating the cbind() call every time n changes. These methods:

  • Are scalable: No manual edits needed if you add/remove vol_* columns
  • Are less error-prone: No chance of missing a variable or typos in hardcoded names
  • Are more readable: Anyone looking at the code can immediately understand what's being summed

内容的提问来源于stack exchange,提问作者Hubert Chicoine

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 23:12:28