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

如何在R中计算数据框数值列与对应列均值的差值?

问题:如何对data.frame指定列做均值中心化处理?

你有如下结构的data.frame:

structure(list(Date = structure(c(18605, 18604, 18598, 18597, 18590, 18584, 18583, 18578, 18570, 18569, 18563, 18562, 18557, 18549, 18548, 18542, 18541, 18536, 18534, 18529, 18521, 18520, 18515, 18508, 18500, 18499, 18493, 18492, 18486, 18485, 18479, 18478, 18472, 18471, 18465, 18464, 18458, 18457, 18450, 18445, 18444, 18437, 18436, 18430, 18429, 18424, 18416, 18415, 18410, 18409, 18403, 18402, 18396, 18388, 18387, 18381, 18380, 18374, 18373, 18368, 18367, 18360, 18359, 18354, 18340, 18338, 18331, 18325, 18317, 18312, 18289, 18282, 18275, 18268), class = "Date"), V1 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.3, 0, 0, 0, 0, 0.4, 0, 0, 0, 0, 0.2, 0, 0, 0, 0, 0.7, 0, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0.3, 0, 0, 0, 0, 0, 0.4, 0, 0, 0, 0.3, 0, 0, 0, 0, 0, 0, 0, 0, 0.6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), V2 = c(0, 0, 0.1, 0, 0, 0.1, 0, 0.2, 0, 0.2, 0.1, 0, 0.2, 0.2, 0, 0.1, 0, 0, 0.1, 0, 0.2, 0, 0, 0.4, 0.2, 0, 0.3, 0, 0.2, 0, 0.3, 0, 0.6, 0, 0.4, 0, 0, 0.2, 0, 0.4, 0.6, 0, 0.3, 0, 0.2, 0.7, 0, 0.1, 0.3, 0, 0.2, 0, 0, 0, 0.3, 0, 0.1, 0.3, 0, 0, 0.3, 0.2, 0, 0, 0, 0, 0.6, 0, 0.4, 0, 0.2, 0, 0, 0.2), V3 = c(0, 0.3, 0, 0.3, 0.4, 0, 0.2, 0, 0.3, 0, 0, 0.2, 0, 0, 0.2, 0, 0.2, 0, 0, 0.1, 0, 0.2, 0, 0, 0, 0.3, 0, 0, 0, 0.4, 0, 0.3, 0, 0.7, 0, 0.2, 0.5, 0.4, 0, 0.4, 0, 0.8, 0.4, 0, 0.2, 0.6, 0.3, 0.2, 0, 0, 0, 0.4, 0.4, 0, 0.2, 0.3, 0, 0.2, 0.3, 0.4, 0, 0.7, 0, 0, 1.4, 0, 0, 1.4, 0, 1, 0, 0, 0.3, 0), V4 = c(0, 0.4, 0, 0.1, 0.1, 0, 0.1, 0, 0, 0.1, 0, 0.1, 0.2, 0, 0.2, 0, 0.2, 0.3, 0, 0, 0, 0.2, 0.3, 0.3, 0, 0, 0, 0.5, 0, 0.6, 0, 0.7, 0, 0, 0, 1.2, 1, 0, 0.3, 0, 1.1, 0, 0, 0.4, 0, 0, 0, 0, 0.2, 0.2, 0, 0, 0.2, 0, 0, 0.1, 0, 0, 0, 0.2, 0.3, 0, 0.2, 0.3, 0, 1.8, 0, 0, 0, 0, 0, 0.2, 0, 0)), row.names = c(NA, -74L), class = c("tbl_df", "tbl", "data.frame"))

需求是将V1、V2、V3、V4列的数值替换为该列数值与对应列均值的差值(即均值中心化),但尝试执行df <- df %>% mutate(across(2, x - mean()))时出现计算错误,以下是正确实现方式:


正确实现代码

方式一:使用公式形式(推荐)

library(dplyr)

df <- df %>%
  mutate(across(V1:V4, ~ .x - mean(.x, na.rm = TRUE)))

方式二:使用匿名函数

library(dplyr)

df <- df %>%
  mutate(across(V1:V4, function(x) x - mean(x, na.rm = TRUE)))

错误原因说明

你之前的代码有两个问题:

  1. 列范围错误:across(2)仅指定了第2列(V1),没有覆盖需要处理的V2-V4列;
  2. 函数定义错误:x - mean()缺少参数绑定,R无法识别x指代当前列,必须用公式(~ .x)或匿名函数(function(x))来明确处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 23:40:22