我有一个年龄变量,我需要将其重新编码为类别。我已经看到这两个问题,但是答案似乎只会在内存中产生一些东西。当我打开data.table时,新的分类变量不存在。我看不到它,我也无法使用它。但是我可以运行一个频率。但是我需要它成为它自己的变量。
R code to categorize age into group/ bins/ breaks
Convert Age variable into ordinal variable
我如何将连续变量转换为因数,然后再得到有形变量? 或者,我该如何处理内存中创建的所有内容并将其变为现实?
`setDT(LSSCM)[client_age <17, agegroup := "0-17"]`
`LSSCM[client_age >=18 & client_age <=24, agegroup := "18-24"]`
`LSSCM[client_age >=25 & client_age <=30, agegroup := "25-30"]`
`LSSCM[client_age >=31 & client_age <=39, agegroup := "31-39"]`
`LSSCM[client_age >=40 & client_age <=54, agegroup := "40-54"]`
`LSSCM[client_age >=55 & client_age <=64, agegroup := "55-64"]`
`LSSCM[client_age >=65 & client_age <=75, agegroup := "65-75"]`
`LSSCM[client_age >=76, agegroup := "76+"]`
LSSCM$age_cat <- case_when(LSSCM$client_age <= 17 ~ '0-17',
between(LSSCM$client_age, 18, 24) ~ '18-24',`
between(LSSCM$client_age, 25, 30) ~ '25-30',`
between(LSSCM$client_age, 31, 39) ~ '31-39',`
between(LSSCM$client_age, 40, 54) ~ '40-54',`
between(LSSCM$client_age, 55, 64) ~ '55-64',`
between(LSSCM$client_age, 65, 75) ~ '65-75',`
LSSCM$client_age >= 76 ~ '76+')`
答案 0 :(得分:1)
只需将首选解决方案的结果分配到data.frame的列中。例如:
df$agegroups<-cut(df$ages, breaks=c(20, 30, 40, 50), right = FALSE)
例如:
df<-data.frame(age = c(55, 60, 65, 70, 75, 80, 85, 90, 95))
df
age
1 55
2 60
3 65
4 70
5 75
6 80
7 85
8 90
9 95
df$age_cat<-cut(df$age, breaks=c(0,17,24,30,39,54,64,75), right = FALSE)
df
age age_cat
1 55 [54,64)
2 60 [54,64)
3 65 [64,75)
4 70 [64,75)
5 75 <NA>
6 80 <NA>
7 85 <NA>
8 90 <NA>
9 95 <NA>