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

R语言中用dplyr将指定列列表与weight列相乘报错求助

问题描述

需要实现数据框中指定列(排除Id和weight)与weight列相乘的功能,编写的代码如下:

#df 1
Id = c("1", "2", "3", "4")
Persons = c(300, 400, 200, 5000)
Houses = c(20, 40, 10, 23)
Ages =  c(45, 34, 50, 44)
Races = c(1, 3, 1, 2)
weight = c(0.9, 1.2, 0.8, 1.1)

estimates = data.frame(Id, Persons, Houses, Ages, Races, weight)
list <- as.list(colnames(subset(estimates, select = -c(Id, weight))))
estimates <- estimates %>% mutate_each(funs(.*weight), . %in% list)

运行后出现错误:

Error in as_indices_impl(): ! Must subset columns with a valid
subscript vector. ✖ Subscript has the wrong type logical. ℹ It must
be numeric or character.

问题原因
  1. mutate_each 是dplyr旧版本的函数,目前已被mutate_at等新版函数替代,语法存在兼容性问题
  2. . %in% list 的写法错误:mutate_each(及新版列处理函数)要求传入列名/列索引向量,而该写法返回的是逻辑向量,不符合参数要求
解决方法

方案1:使用新版dplyr函数(推荐)

用mutate_at搭配vars()选择目标列,直接完成列乘法操作:

# 构造数据
Id = c("1", "2", "3", "4")
Persons = c(300, 400, 200, 5000)
Houses = c(20, 40, 10, 23)
Ages =  c(45, 34, 50, 44)
Races = c(1, 3, 1, 2)
weight = c(0.9, 1.2, 0.8, 1.1)

estimates = data.frame(Id, Persons, Houses, Ages, Races, weight)

# 方式一:直接排除不需要处理的列
library(dplyr)
estimates <- estimates %>% 
  mutate_at(vars(-Id, -weight), ~ . * weight)

# 方式二:先定义目标列向量再传入
target_cols <- setdiff(colnames(estimates), c("Id", "weight"))
estimates <- estimates %>% 
  mutate_at(vars(target_cols), ~ . * weight)

方案2:兼容旧版dplyr(不推荐)

如果必须使用mutate_each,需用one_of()包装列名向量,确保参数类型正确:

list <- colnames(subset(estimates, select = -c(Id, weight)))  # 无需转成list,向量即可
estimates <- estimates %>% 
  mutate_each(funs(. * weight), one_of(list))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:20:21