Cleaning up factor levels (collapsing multiple levels/labels)

后端 未结 10 1921
礼貌的吻别
礼貌的吻别 2020-11-22 14:27

What is the most effective (ie efficient / appropriate) way to clean up a factor containing multiple levels that need to be collapsed? That is, how to combine two or more fa

10条回答
  •  太阳男子
    2020-11-22 14:55

    Similar to @Aaron's approach, but slightly simpler would be:

    x <- c("Y", "Y", "Yes", "N", "No", "H")
    x <- factor(x)
    # levels(x)  
    # [1] "H"   "N"   "No"  "Y"   "Yes"
    # NB: the offending levels are 1, 2, & 4
    levels(x)[c(1,2,4)] <- c(NA, "No", "Yes")
    x
    # [1] Yes  Yes  Yes  No   No   
    # Levels: No Yes
    

提交回复
热议问题