【问题标题】:recode multiple columns `mutate_at` with unused arguments error使用未使用的参数错误重新编码多列`mutate_at`
【发布时间】:2020-03-27 08:32:39
【问题描述】:

我正在尝试使用相同的编码方案重新编码多列中的值。我使用来自这个post 的代码mutate_at 但没有用。

我的数据框是这样的,我想重新编码“Neutral = 3”和“Agree = 4”

A              B            C
Neutral       Agree        Neutral
Neutral       Agree        Agree
Agree         Neutral      Neutral

我的代码

df %>%
  mutate_at(c("A", "B", "C"), funs(as.character)) %>%
  mutate_at(c("A", "B", "C"), funs(recode(.,"Neutral"=3, "Agree"=4)))

错误显示

Error in recode(A, Neutral = 3, Agree = 4) : 
  unused arguments (Neutral = 3, Agree = 4)

谢谢!

【问题讨论】:

  • 顺便说一句:除了警告...您的代码在我的机器上使用 dplyr 0.8.5 工作正常

标签: r dplyr recode


【解决方案1】:

你可以使用:

library(dplyr)
df %>% mutate_all(~recode(., "Neutral"=3, "Agree"=4))
#If there are other columns
#df %>%  mutate_at(vars(A:C), ~recode(., "Neutral"=3, "Agree"=4))

#  A B C
#1 3 4 3
#2 3 4 4
#3 4 3 3

如果可以取的值有限,我们也可以使用ifelse/case_when

df %>%  mutate_all(~ifelse(.  == "Neutral", 3, 4))

或者在基础 R 中使用lapply

df[] <- lapply(df, function(x) ifelse(x == "Neutral", 3, 4))

【讨论】:

    猜你喜欢
    • 2019-08-12
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 2018-04-07
    • 2018-05-11
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    相关资源
    最近更新 更多