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 typelogical. ℹ It must
be numeric or character.
问题原因
mutate_each是dplyr旧版本的函数,目前已被mutate_at等新版函数替代,语法存在兼容性问题. %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
相关产品推荐
相关产品推荐

