提问人:sdS 提问时间:3/9/2023 最后编辑:akrunsdS 更新时间:3/9/2023 访问量:91
使用列名称非常多个条件的mutate_at对变量进行重新编码
Recode variables using mutate_at where column names very more than one condition
问:
编辑:我实际上有需要重新编码的文本。更新以反映 - 我有一组带有标签“js”的变量和其他带有 js_R_ 的变量。我需要单独对这两个变量进行重新编码,这意味着所有“js”列都需要使用相同的规则进行重新编码,但使用与“js_R_”不同的规则,反之亦然。假设我的数据集如下所示:
d1 <- data.frame(js_1 = c("Strongly agree", "Agree", "Neither", "Disagree", "Strongly disagree"),
js_R_2 = c("Strongly disagree", "Disagree", "Neither", "Agree", "Strongly agree"))
我想做的是为包含“js”但不包含“_R _”的列指定重新编码规则。通常,我会做这样的事情
mutate_at(
vars(contains("js"),
funs(case_when(.== "Strongly disagree"~1,
.== "Disagree"~2,
.== "Neither"~3,
.== "Agree"~4,
.== "Strongly agree" ~5)))
但我在向我的命令添加多个标准方面一直没有成功。vars
任何帮助都是值得赞赏的!
答:
2赞
harre
3/9/2023
#1
我们还可以使用多个条件,继续:contains()
library(dplyr)
# Using case_when like OP
d1 |>
mutate(
across(contains("js") & !contains("R"),
~ case_when(. == "Strongly disagree" ~ 1,
. == "Disagree" ~ 2,
. == "Neither" ~ 3,
. == "Agree" ~ 4,
. == "Strongly agree" ~ 5))
)
# Using case_match (recode in dplyr v. < 1.1.0)
d1 |>
mutate(
across(contains("js") & !contains("R"),
~ case_match(.,
"Strongly disagree" ~ 1,
"Disagree" ~ 2,
"Neither" ~ 3,
"Agree" ~ 4,
"Strongly agree" ~ 5))
)
输出:
js_1 js_R_2
1 5 Strongly disagree
2 4 Disagree
3 3 Neither
4 2 Agree
5 1 Strongly agree
mutate_at
等被取代并被弃用,但如果您愿意:funs()
d1 |>
mutate_at(
vars(contains("js") & !contains("R")),
funs(case_when(. == "Strongly disagree" ~ 1,
. == "Disagree" ~ 2,
. == "Neither" ~ 3,
. == "Agree" ~ 4,
. == "Strongly agree" ~ 5))
)
下一个:Power BI 相对日期切片器
评论