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

在R语言中实现用指定列减去每行最大值生成新列

实现方案

不用折腾maxstat包,用dplyr的mutate配合行操作就能轻松完成需求,具体做法如下:

步骤说明

  1. 先确保装了dplyr包,没装的话先执行install.packages("dplyr"),然后加载它
  2. 用rowwise()让数据按行分组,接着用c_across()选中所有列算出每行的最大值,最后用col1减去这个最大值生成new列

完整代码

# 安装并加载dplyr(未安装则执行install.packages("dplyr"))
library(dplyr)

# 构造你的输入数据框
df <- tibble(
  col1 = c(1, 3, 2),
  col2 = c(3, 7, 2),
  col3 = c(2, 4, 6),
  col4 = c(3, 1, 8),
  col5 = c(5, 2, 3)
)

# 生成new列
df_result <- df %>%
  rowwise() %>%
  mutate(new = col1 - max(c_across(col1:col5))) %>%
  ungroup()

# 查看结果
print(df_result)

运行输出

# A tibble: 3 × 6
   col1  col2  col3  col4  col5   new
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     3     2     3     5    -4
2     3     7     4     1     2    -4
3     2     2     6     8     3    -6

对应你期望输出的调整

你给的期望结果里第二行col1是9,要是实际输入就是9,把代码里col1的第二个值改成9就行:

df <- tibble(
  col1 = c(1, 9, 2),
  col2 = c(3, 7, 2),
  col3 = c(2, 4, 6),
  col4 = c(3, 1, 8),
  col5 = c(5, 2, 3)
)

跑出来的结果就和你期望的完全一致:

# A tibble: 3 × 6
   col1  col2  col3  col4  col5   new
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     3     2     3     5    -4
2     9     7     4     1     2     2
3     2     2     6     8     3    -6

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:03:20