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

如何在R语言data.frame中批量将对应数量列与单价列相乘?

实现quantity与对应priceperunit列相乘的方法

你的数据框包含ID列、156个quantity_*列及对应的156个priceperunit_q*列,以下是两种高效实现每对列相乘的方案:

方法一:基础R原生实现

适合习惯基础语法的场景,无需额外安装包:

# 假设数据框名为df
# 筛选所有quantity列的名称
quant_cols <- grep("^quantity_", names(df), value = TRUE)
# 匹配对应的price列名称(替换前缀)
price_cols <- sub("quantity_", "priceperunit_q", quant_cols)

# 向量化计算乘积并合并回原数据框
total_data <- df[, quant_cols] * df[, price_cols]
colnames(total_data) <- sub("quantity_", "total_", quant_cols)
df <- cbind(df, total_data)

如果需要逐列调试,也可以用循环实现:

for (i in seq_along(quant_cols)) {
  new_col_name <- paste0("total_", sub("quantity_", "", quant_cols[i]))
  df[[new_col_name]] <- df[[quant_cols[i]]] * df[[price_cols[i]]]
}

方法二:tidyverse/dplyr 管道式实现

适合数据重塑场景,代码逻辑更直观:

library(dplyr)
library(tidyr)

df_processed <- df %>%
  # 将宽格式转为长格式,拆分列名中的数字标识
  pivot_longer(
    cols = -ID,
    names_to = c(".value", "item_num"),
    names_pattern = "(quantity_|priceperunit_q)(\\d+)"
  ) %>%
  # 计算单类总金额
  mutate(total = quantity_ * priceperunit_q) %>%
  # 转回宽格式,恢复原有列结构并新增total列
  pivot_wider(
    id_cols = ID,
    names_from = item_num,
    values_from = c(quantity_, priceperunit_q, total)
  )

注:names_pattern通过正则表达式将列名拆分为前缀类型和数字标识两部分,确保quantity与price列能精准配对。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:57:31