我想将值从 1 到 10(数字)的变量重新编码为 5 个值的因子变量。我正在使用命令 dplyr::recode,但它不起作用。我知道如何使用 cut 函数或 case_when 来完成此操作,但我想知道是否有办法使用 recode 函数来完成此操作。
我正在尝试此代码,但显示错误:
df <- df %>%
mutate(x_rec = as.factor(recode(x, '1:2' = '1',
'3:4' = '2', '5:6'= '3',
'7:8' = '4', '9:10' = '5')))
输出显示:
Warning messages:
1: Problem while computing `x_rec = as.factor(...)`.
ℹ NAs introduced by coercion
2: Problem while computing `x_rec = as.factor(...)`.
ℹ Unreplaced values treated as NA as `.x` is not compatible.
我尝试使用 drop_na(),但不起作用。我还尝试使用参数“.default = NA”和“.missing = NA”,但它说这是一个未使用的参数。如果有人能帮助我那就太好了。非常感谢。
最佳答案
recode()
仅当您的输入已经是因子变量时才会为您提供帮助。使用 cut()
将数值转换为因子水平。
set.seed(42)
x <- sample(1:10, 10, replace = TRUE)
cut(x,
breaks = c(0, 2, 4, 6, 8, 10),
labels = c("1", "2", "3", "4", "5"))
#> [1] 1 3 1 5 5 2 1 5 1 4
#> Levels: 1 2 3 4 5
创建于 2023-03-09 reprex v2.0.2
关于r - 如何将一系列值(数字)重新编码为因子变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75689555/