崩溃的因素

Collapsing of factors

forcats::fct_collapse 的因子水平崩溃导致意外结果

它遵循 fct_collapse

示例中的一些修改代码
require(forcats)
partyid2 <- fct_collapse(gss_cat$partyid,
                         missing = c("No answer"),
                         other = "Other party",
                         rep = c("Strong republican", "Not str republican"),
                         ind = c("Ind,near rep", "Independent", "Ind,near dem"),
                         dem = c("Not str democrat", "Strong democrat"),
                         group_other = TRUE
)
table(gss_cat$partyid, partyid2)

例如,为什么 'Strong democrat' 关卡最终会进入 'Other' 关卡?

非常感谢您的提示,我做错了什么。

partyid2
                     missing other  rep  ind  dem Other
  No answer              154     0    0    0    0     0
  Don't know               0     1    0    0    0     0
  Other party              0     0  393    0    0     0
  Strong republican        0     0 2314    0    0     0
  Not str republican       0     0    0 3032    0     0
  Ind,near rep             0     0    0 1791    0     0
  Independent              0     0    0 4119    0     0
  Ind,near dem             0     0    0    0 2499     0
  Not str democrat         0     0    0    0 3690     0
  Strong democrat          0     0    0    0    0  3490

示例中的代码不正确。它改变了顺序。保持相同的顺序

partyid2 <- fct_collapse(levels(gss_cat$partyid),
                         missing = c("No answer"),
                          other = "Other party",
                          rep = c("Strong republican", "Not str republican"),
                          ind = c("Ind,near rep", "Independent", "Ind,near dem"),
                          dem = c("Not str democrat", "Strong democrat"),
                          group_other = TRUE
 )[gss_cat$partyid] 
table(gss_cat$partyid, partyid2)
#              partyid2
#                     missing other  rep  ind  dem Other
#  No answer                0     0    0  154    0     0
#  Don't know               1     0    0    0    0     0
#  Other party              0     0    0    0  393     0
#  Strong republican        0     0    0    0    0  2314
#  Not str republican       0     0    0 3032    0     0
#  Ind,near rep             0     0 1791    0    0     0
#  Independent              0     0 4119    0    0     0
#  Ind,near dem             0  2499    0    0    0     0
#  Not str democrat         0     0    0 3690    0     0
#  Strong democrat          0     0    0    0 3490     0