0

我有以下数据框:

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'。你知道为什么会这样吗?我想这与我的因子的值是数字但没有找到处理它的方法有关。任何的想法?

有些帖子处理类似的问题,但在这种情况下对我没有帮助:

用数值替换因子

两列的连接因子水平

4

2 回答 2

2

一个简单的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中引用的内容。如果我们删除它,它会按预期工作,但不会给其他组带来任何价值。

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并将在下一个版本中提供。

于 2020-01-29T11:28:08.200 回答
1

这是一种替代方法,使用 dplyr::recode()

df %>% 
  mutate(
    a = as.character(a),
    a_new = recode(a,
                   '1' = 'group1', 
                   '2' = 'group2', 
                   '3' = 'group1', 
                   '4' = 'group1', 
                   '5' = 'Other'))
于 2020-01-29T12:27:33.350 回答