【发布时间】:2021-08-17 17:53:03
【问题描述】:
我正在尝试在我的整个数据集上使用 dplyr 的 cross 和 case_when,所以每当它看到“强烈同意”时,它会将其更改为数字 5,“同意”到数字 4,依此类推。我试过查看这个answer,但我收到了一个错误,因为我的数据集有逻辑列和数字列,并且 R 正确地说“同意”不能在逻辑列中,等等。
这是我的数据:
library(dplyr)
test <- tibble(name = c("Justin", "Corey", "Sibley"),
date = c("2021-08-09", "2021-10-29", "2021-01-01"),
s1 = c("Agree", "Neutral", "Strongly Disagree"),
s2rl = c("Agree", "Neutral", "Strongly Disagree"),
f1 = c("Strongly Agree", "Disagree", "Strongly Disagree"),
f2rl = c("Strongly Agree", "Disagree", "Strongly Disagree"),
exam = c(90, 99, 100),
early = c(TRUE, FALSE, FALSE))
理想情况下,我想要一个可以让我遍历整个数据集的命令。但是,如果不能这样做,我希望有一个参数允许我使用多个 cross(contains()) 参数(即,这里包含“s”或“f”)。
这是我已经尝试过但无济于事的方法:
library(dplyr)
test %>%
mutate(across(.),
~ case_when(. == "Strongly Agree" ~ 5,
. == "Agree" ~ 4,
. == "Neutral" ~ 3,
. == "Disagree" ~ 2,
. == "Strongly Disagree" ~ 1,
TRUE ~ NA))
Error: Problem with `mutate()` input `..1`.
x Must subset columns with a valid subscript vector.
x Subscript has the wrong type `tbl_df<
name: character
date: character
s1 : character
s2rl: character
f1 : character
f2rl: character
exam: double
>`.
ℹ It must be numeric or character.
ℹ Input `..1` is `across(.)`.
【问题讨论】: