在 R 中重新编码未产生所需的输出
Recode in R not producing desired output
我正在尝试将年龄变量重新编码为 R 中的三个类别,但它没有正确分配它们:
data_2017_18$ageband3 <-
dplyr::recode(data_2017_18$age, '1:30' = 1L,
'31:50' = 2L, '51:99' = 3L)
我假设与年龄的交叉表是:
年龄段
1个
2个
3
但是,当我查看数据集时,它会将每个人的年龄值放入一个 'ageband3' 变量中。
感谢任何建议。
谢谢!
在 R 中有很多方法可以完成这个任务,这是我的建议
tibble(age=1:99L) %>%
mutate(age_recoded=if_else(age %in% c(1:30),1L,
if_else(age %in% c(31:50),2L,3L))) %>%
count(age_recoded)
。希望对您有所帮助。
我觉得没必要recode
。最简单的解决方案是使用 cut
:
data_2017_18$ageband3 <- cut(data_2017_18$age, cut(1:100, breaks = c(0, 30,50, Inf))
如果您喜欢标记级别 1,2 和 3,请使用 cut(data_2017_18$age, breaks = c(0, 30,50, Inf), labels = c(1,2,3))
。但是 R
可以很好地处理间隔值(例如 [0,30]
)
我正在尝试将年龄变量重新编码为 R 中的三个类别,但它没有正确分配它们:
data_2017_18$ageband3 <-
dplyr::recode(data_2017_18$age, '1:30' = 1L,
'31:50' = 2L, '51:99' = 3L)
我假设与年龄的交叉表是:
年龄段 1个 2个 3
但是,当我查看数据集时,它会将每个人的年龄值放入一个 'ageband3' 变量中。
感谢任何建议。
谢谢!
在 R 中有很多方法可以完成这个任务,这是我的建议
tibble(age=1:99L) %>%
mutate(age_recoded=if_else(age %in% c(1:30),1L,
if_else(age %in% c(31:50),2L,3L))) %>%
count(age_recoded)
。希望对您有所帮助。
我觉得没必要recode
。最简单的解决方案是使用 cut
:
data_2017_18$ageband3 <- cut(data_2017_18$age, cut(1:100, breaks = c(0, 30,50, Inf))
如果您喜欢标记级别 1,2 和 3,请使用 cut(data_2017_18$age, breaks = c(0, 30,50, Inf), labels = c(1,2,3))
。但是 R
可以很好地处理间隔值(例如 [0,30]
)