我有以下数据框:
df = data.frame(a = 1:5) %>% as_tibble()
我想将值1和3折叠为'group1',将2和4折叠为'group2',将其他值(例如5)折叠为'Other'。我以为fct_collapse()将是完美的功能,但它做的事情很奇怪...
df %>%
mutate(
a = as.character(a),
a_collapse = fct_collapse(a,
group1=c('1', '3'),
group2 = c('2', '4'),
group_other = TRUE))
但是,值3为'group2'而不是'group1'。你知道为什么会这样吗?我想这与事实有关,即我的因子的值是数字,但没有找到解决该问题的方法。有什么主意吗?
有些帖子处理类似的问题,但在这种情况下并没有帮助我:
简单的case_when
?
library(dplyr)
df %>%
mutate(a_collapse = factor(case_when(a %in% c(1, 3)~"group1",
a %in% c(2, 4) ~"group2",
TRUE ~ 'Other')))
# A tibble: 5 x 2
# a a_collapse
# <int> <fct>
#1 1 group1
#2 2 group2
#3 3 group1
#4 4 group2
#5 5 Other
就fct_collapse
而言,问题似乎出在Github上group_other
中所引用的issue上。如果我们删除它,它会按预期工作,但不会给其他组任何价值。
df %>%
mutate(
a = as.character(a),
a_collapse = forcats::fct_collapse(a,
group1=c('1', '3'),
group2 = c('2', '4')))
# A tibble: 5 x 2
# a a_collapse
# <chr> <fct>
#1 1 group1
#2 2 group2
#3 3 group1
#4 4 group2
#5 5 5
此错误已在forcats
的开发版本中修复,将在下一版本中提供。
这里是替代方法,使用dplyr :: recode()
df %>%
mutate(
a = as.character(a),
a_new = recode(a,
'1' = 'group1',
'2' = 'group2',
'3' = 'group1',
'4' = 'group1',
'5' = 'Other'))