结合R中的因子水平

时间:2016-04-12 09:15:17

标签: r dplyr

我想把级别“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)]))

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:3)

一个选项是来自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)

答案 2 :(得分:0)

如何使用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