我有一个很大的数据集,如下面的示例所示。标头中带有As的列的代码为1到4,带有Bs的列的代码为1到3。
library(dplyr)
d <- data.frame(
ID = 1:10,
A = sample(x = 1:4, size = 10, replace = T),
AA = sample(x = 1:4, size = 10, replace = T),
B = sample(x = 1:3, size = 10, replace = T),
BB = sample(x = 1:3, size = 10, replace = T)
)
是否有一种巧妙的方法可以使用dplyr中的管道将标头中带有As的列和带有Bs的列中的值重新编码为以下字符串?
这是真实数据集的简化版本。
答案 0 :(得分:0)
通过使用dplyr中的mutate_at,可以完成从数字代码到字符串的重新编码。首先必须将要重新编码的列从数字强制转换为字符,否则将出现错误消息。
library(dplyr)
d <- data.frame(
ID = 1:10,
A = sample(x = 1:4, size = 10, replace = T),
AA = sample(x = 1:4, size = 10, replace = T),
B = sample(x = 1:3, size = 10, replace = T),
BB = sample(x = 1:3, size = 10, replace = T))
d_recoded <- d %>% mutate_at(vars(-contains("ID")), funs(as.character)) %>%
mutate_at(vars(contains("A"), -contains("ID")), funs(case_when(. == 1 ~ "Green", . == 2 ~ "Yellow", . == 3 ~ "Orange", . == 4 ~ "Red"))) %>%
mutate_at(vars(contains("B"), -contains("ID")), funs(case_when(. == 1 ~ "Green", . == 2 ~ "Yellow", . == 3 ~ "Red")))