R 因子崩溃
使用forcats::fct_collapse折叠因子级别会导致意外结果 它遵循fct_崩溃示例中的一些修改代码R 因子崩溃,r,forcats,R,Forcats,使用forcats::fct_collapse折叠因子级别会导致意外结果 它遵循fct_崩溃示例中的一些修改代码 require(forcats) partyid2 <- fct_collapse(gss_cat$partyid, missing = c("No answer"), other = "Other party", rep = c
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)
示例中的代码不正确。它改变了顺序。让它保持同样的顺序
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
partyid2示例中的代码不正确。它改变了顺序。让它保持同样的顺序
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
partyid2请检查是否有leading/laging
spacess。尝试fct\u collapse(trimws(gss\u cat$partyid),
trimws()
删除factor类,并在重新编码为factor时产生不同的顺序。示例的不匹配会消失,但会创建新的。好的,然后您必须检查确切的级别级别(gss\u cat$partyid)
并指定这些值。在fct\u折叠中
命名字符向量右侧提供的所有级别
都是级别的实际因子级别(gss\u cat$partyid)
。我看到一个被标记为bug的,该bug似乎与您看到的问题相同。请检查您是否有超前/滞后的空格。尝试fct\u折叠(trimws(gss\u cat$partyid),
trimws()
删除factor类,并在重新编码为factor时产生不同的排序。示例的不匹配消失,但创建了新的。好的,然后您必须检查确切的级别级别(gss\U cat$partyid)
并指定这些值。在fct\u折叠中
命名字符向量右侧提供的所有级别
都是级别的实际因子级别(gss\u cat$partyid)
。我看到了一个被标记为bug的错误,它似乎与您看到的问题相同。实际上是fct\u collapse
的代码不适当地更改了顺序,而不是示例。@Andi。无论如何,这是有效的。我假设是这样。您想让它正常工作/当然,再次感谢!但在某个时候(在mutate和分组材料中…)我会忘记重新排序并保留缺陷。实际上是fct_collapse
的代码不适当地更改了顺序,而不是示例。@Andi。无论如何,这是有效的。我假设。你想让它正常工作/当然,再次感谢!但在某个时候(在mutate和分组材料中…)我将忘记重新排序并保留缺陷。