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

R语言如何将fixed_factor列每行值批量添加到所有line_1_rec开头的列

问题描述

我是R语言初学者,现有如下结构的dataframe:

df <- structure(list(row.names = 1:5, date = c("01-01-2017", "10-01-2017", 
"10-04-2017", "11-04-2017", "12-04-2017"), fixed_factor = c(NA, 
3L, 2L, 5L, 10L), line_1_rec_1_mean = c(0.5, 0.1, 0.05, 0.05, 
0.1), line_1_rec_2_mean = c(6, 5, 3, 2, 0.9), line_1_rec_3_mean = c(88L, 
3L, 4L, 3L, 7L), line_1_rec_5_mean = c(6, 0.2, 0.7, 0.6, 3), 
    line_1_rec_6_mean = c(50L, 1L, 5L, 8L, 2L)), row.names = c(NA, 
-5L), class = "data.frame")

原始数据预览:

row.names       date fixed_factor line_1_rec_1_mean line_1_rec_2_mean line_1_rec_3_mean line_1_rec_5_mean line_1_rec_6_mean
1         1 01-01-2017           NA               0.5                 6                88                 6                50
2         2 10-01-2017            3               0.1                 5                 3               0.2                 1
3         3 10-04-2017            2              0.05                 3                 4               0.7                 5
4         4 11-04-2017            5              0.05                 2                 3               0.6                 8
5         5 12-04-2017           10               0.1               0.9                 7                 3                 2

我实际使用的dataframe包含1500余列、365行。需要实现的需求为:将每行的fixed_factor列值,添加到除前3列之外的所有以line_1_rec开头的列的对应数值上,最终生成新的dataframe,预期结果如下:

row.names       date fixed_factor line_1_rec_1_mean line_1_rec_2_mean line_1_rec_3_mean line_1_rec_5_mean line_1_rec_6_mean
1         1 01-01-2017           NA              0.50               6.0                88               6.0                50
2         2 10-01-2017            3              3.10               8.0                 6               3.2                 4
3         3 10-04-2017            2              2.05               5.0                 6               2.7                 7
4         4 11-04-2017            5              5.05               7.0                 8               5.6                13
5         5 12-04-2017           10             10.10              10.9                17              13.0                12

解决方案

以下两种方案均适配上千列的大表场景,结果和预期完全一致:

方案1:基础R实现(无需加载额外包,运算速度快)

# 筛选所有需要修改的目标列
target_cols <- startsWith(colnames(df), "line_1_rec")
# 按行批量相加,fixed_factor为NA的行自动保留原数值
df[target_cols] <- df[target_cols] + df$fixed_factor

方案2:dplyr实现(语法直观易读)

library(dplyr)
df_new <- df %>%
  mutate(across(starts_with("line_1_rec"), ~ .x + fixed_factor))

两种方案都不需要手动指定列序号,后续列数变化也无需修改代码,可自动适配所有以line_1_rec开头的列。


内容的提问来源于stack exchange,提问作者R.Ha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 08:54:02