【发布时间】:2013-03-20 20:05:12
【问题描述】:
我很少使用因子,并且通常认为它们是可以理解的,但我经常对特定操作的细节感到模糊。目前,我正在对几乎没有观察到“其他”的类别进行编码/折叠,并且正在寻找一种快速的方法来做到这一点——我可能有 20 个级别的变量,但我有兴趣将它们中的一堆折叠成一个。
data <- data.frame(employees = sample.int(1000,500),
naics = sample(c('621111','621112','621210','621310','621320','621330','621340','621391','621399','621410','621420','621491','621492','621493','621498','621511','621512','621610','621910','621991','621999'),
100, replace=T))
这是我的兴趣等级,以及它们在不同向量中的标签。
#levels and labels
top8 <-c('621111','621210','621399','621610','621330',
'621310','621511','621420','621320')
top8_desc <- c('Offices of physicians',
'Offices of dentists',
'Offices of all other miscellaneous health practitioners',
'Home health care services',
'Offices of Mental Health Practitioners',
'Offices of chiropractors',
'Medical Laboratories',
'Outpatient Mental Health and Substance Abuse Centers',
'Offices of optometrists')
我可以使用factor() 调用,将它们全部列举出来,每当一个类别很少观察到时,将它们归类为“其他”。
假设上面的top8 和top8_desc 是实际的前8 位,那么将data$naics 声明为因子变量的最佳方法是什么,以便top8 中的值被正确编码,而其他所有内容都被重新编码作为other?
【问题讨论】: