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

使用mutate_at重编码指定列值报错,求正确实现方法

问题解决

错误原因

你遇到的报错是因为mutate_at的.funs参数要求传入函数、单侧公式(带~)或函数名称,而你直接传入case_when的逻辑表达式,不符合参数格式要求。另外你代码里最后一行big5qflip==5~2和你描述的重编码规则(5←1)不符,需要修正。

正确写法

方法1:修正mutate_at配合case_when

把case_when包裹在单侧公式里,用.指代当前处理的列值:

big5new %>%
  mutate_at(vars(big5qflip), ~ case_when(
    . == 1 ~ 5,
    . == 2 ~ 4,
    . == 3 ~ 3,
    . == 4 ~ 2,
    . == 5 ~ 1
  ))

方法2:更简洁的对称重编码

因为你的重编码是对称互换(1↔5,2↔4,3不变),可以用数学运算替代case_when,代码更高效:

big5new %>%
  mutate_at(vars(big5qflip), ~ 6 - .)

逻辑:6 - 1 = 5、6 - 2 = 4、6 - 3 = 3,完全匹配你的重编码规则。

方法3:使用dplyr最新语法(推荐)

mutate_at已被软弃用,官方推荐用mutate(across(...)),更清晰:

# 简洁版
big5new %>%
  mutate(across(all_of(big5qflip), ~ 6 - .))

# case_when版
big5new %>%
  mutate(across(all_of(big5qflip), ~ case_when(
    . == 1 ~ 5,
    . == 2 ~ 4,
    . == 3 ~ 3,
    . == 4 ~ 2,
    . == 5 ~ 1
  )))

这里all_of(big5qflip)用于明确引用向量中的列名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:55:26