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

R语言两个数据集减法:All数据集coef值减去df1的DR0开头列数值

R数据集减法运算实现方案

由于你生成的All数据集与df1的行顺序、分组对应关系完全一致,直接批量对所有DR0开头的列做减法即可,实现代码如下:

library(dplyr)

# 批量计算coef与所有DR0开头列的差值
result <- All %>%
  # 绑定df1中所有DR0开头的列
  bind_cols(select(df1, starts_with("DR0"))) %>%
  # 遍历所有DR0开头的列,用coef减去对应列值,生成带_res后缀的结果列
  mutate(across(starts_with("DR0"), ~ coef - .x, .names = "{col}_res")) %>%
  # 筛选保留需要的列:标识列+coef+计算后的结果列
  select(date2, Category, coef, ends_with("_res"))

运行后打印result即可得到对应结果,输出示例如下:

> result
       date2 Category coef DR01_res DR02_res DR03_res DR04_res DR05_res DR06_res
1 2021-06-30      FDE    4        0        0       -5       -1       -1        2
2 2021-06-30      ABC    1        0       -1       -4       -3       -3       -3
3 2021-07-01      FDE    6        2        0        2        3        1        3
4 2021-07-01      ABC    3        0        1       -4        1       -1        1

如果你需要保留原始DR0列的数值,删除最后一步select语句即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:45:03