将因子级别重新编码为更少的类别

时间:2017-06-20 03:56:48

标签: r

因子变量中有290个级别,我想从中提取一些(可能是5或6),以便能够可视化每个类别的数据。

我确信有一个功能可以更有效地完成工作。

请帮忙!

PS:没有代码看起来像这样。

Recoder <- c("Victim succombs to Trauma-related Death",
             "Victim succombs to Intentional Violence",
             "Victim succombs to an Accidental Death",
             "Victim succombs to Harsh Weather Conditions",
             "Unknown way to which victim succombed")

temp$reduced_nlevels_death <- if_else(startsWith(temp$cause_of_death,"asp"),Recoder[1],
                              ifelse(startsWith(temp$cause_of_death,"blun"),Recoder[1],
                              ifelse(startsWith(temp$cause_of_death,"deh"),Recoder[1],
                              ifelse(startsWith(temp$cause_of_death,"drow"),Recoder[1],
                              ifelse(startsWith(temp$cause_of_death,"exc"),Recoder[2],
                              ifelse(startsWith(temp$cause_of_death,"exp"),Recoder[1],
                              ifelse(startsWith(temp$cause_of_death,"fel"),Recoder[3],
                              ifelse(startsWith(temp$cause_of_death,"hars"),Recoder[4],
                              ifelse(startsWith(temp$cause_of_death,"exp"),Recoder[1],
                              ifelse(startsWith(temp$cause_of_death,"hit"),Recoder[3],
                              ifelse(startsWith(temp$cause_of_death,"hyp"),Recoder[1],
                              ifelse(startsWith(temp$cause_of_death,"murd"),Recoder[2],
                              ifelse(startsWith(temp$cause_of_death,"pres"),Recoder[1],
                              ifelse(startsWith(temp$cause_of_death,"shot"),Recoder[2],
                              ifelse(startsWith(temp$cause_of_death,"sick"),Recoder[1],
                              ifelse(startsWith(temp$cause_of_death,"star"),Recoder[1],
                              ifelse(startsWith(temp$cause_of_death,"suff"),Recoder[1],
                              ifelse(startsWith(temp$cause_of_death,"unk"),Recoder[5],
                              ifelse(startsWith(temp$cause_of_death,"veh"),Recoder[3],
                              ifelse(startsWith(temp$cause_of_death,"vio"),Recoder[2],
                              "Other"))))))))))))))))))))

0 个答案:

没有答案