【问题标题】:Combining factor level in R [duplicate]R中的组合因子水平[重复]
【发布时间】:2016-04-12 09:15:17
【问题描述】:

我想将级别“A”、“B”合并为“A+B”。我通过以下方式成功做到了这一点:

x <- factor(c("A","B","A","C","D","E","A","E","C"))
x
#[1] A B A C D E A E C
#Levels: A B C D E
l <- c("A+B","A+B","C","D+E","D+E")
factor(l[as.numeric(x)])
#[1] A+B A+B A+B C   D+E D+E A+B D+E C  
#Levels: A+B C D+E

有没有更简单的方法来做到这一点? (即更易于解释的函数名称,例如 combine.factor(f, old.levels, new.levels) 将有助于更容易理解代码。)

另外,我试图找到一个命名良好的函数,它可能与 dplyr 包中的数据框一起使用,但没有运气。最接近的实现是

df %>% mutate(x = factor(l[as.numeric(x)]))

【问题讨论】:

  • 您不需要as.numeric,即factor(l[x]) 也可以。并且您可以轻松编写自己的combine.factor 函数
  • levels(x)&lt;-l 也有效。

标签: r dplyr


【解决方案1】:

现在使用 forcats 包中的 fct_collapse() 可以轻松完成此操作。

x <- factor(c("A","B","A","C","D","E","A","E","C"))

library(forcats)
fct_collapse(x, AB = c("A","B"), DE = c("D","E"))

#[1] AB AB AB C  DE DE AB DE C 
#Levels: AB C DE

【讨论】:

    【解决方案2】:

    一个选项是recode 来自car

    library(car)
    recode(x, "c('A', 'B')='A+B';c('D', 'E') = 'D+E'")
    #[1] A+B A+B A+B C   D+E D+E A+B D+E C  
    #Levels: A+B C D+E
    

    它也应该适用于dplyr

    library(dplyr)
    df %>%
       mutate(x= recode(x, "c('A', 'B')='A+B';c('D', 'E') = 'D+E'"))
    #    x
    #1 A+B
    #2 A+B
    #3 A+B
    #4   C
    #5 D+E
    #6 D+E
    #7 A+B
    #8 D+E
    #9   C
    

    数据

    df <- data.frame(x)
    

    【讨论】:

      【解决方案3】:

      使用ifelse() 来创建一个新因子怎么样?

      x = factor(c("A","B","A","C","D","E","A","E","C"))
      # chained comparisons, a single '|' works on the whole vector
      y = as.factor(
          ifelse(x=='A'|x=='B',
              'A+B',
              ifelse(x=='D'|x=='E','D+E','C')
          )
      )
      > y
      [1] A+B A+B A+B C   D+E D+E A+B D+E C  
      Levels: A+B C D+E
      
      # using %in% to search
      z = as.factor(
          ifelse(x %in% c('A','B'),
              'A+B',
              ifelse(x %in% c('D','E'),'D+E','C'))
      )
      > z
      [1] A+B A+B A+B C   D+E D+E A+B D+E C  
      Levels: A+B C D+E
      

      如果您不想在上面的因子级别C 中硬编码,或者如果您有多个不需要合并的因子级别,则可以使用以下内容。

      # Added new factor levels
      x = factor(c("A","B","A","C","D","E","A","E","C","New","Stuff","Here"))
      w = as.factor(
          ifelse(x %in% c('A','B'),
              'A+B',
              ifelse(x %in% c('D','E'),
                  'D+E',
                  as.character(x) # without the cast it's numeric
              )
          )
      )
      > w
      [1] A+B   A+B   A+B   C     D+E   D+E   A+B   D+E   C     New   Stuff Here
      Levels: A+B C D+E Here New Stuff
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-07
        • 2014-11-14
        • 1970-01-01
        相关资源
        最近更新 更多