合并几个因子变量

问题描述 投票:0回答:2

这是我之前提出的一个问题的后续问题:Combining Survey Items in R/ Recoding NAs

我有一个数据框架,它有多个因子变量,我想把它们组合成一个变量。

ID      REGIONA REGIONB REGIONC
A        North     NA      NA
A        South     NA      NA
B        NA      East      NA
B        NA      West      NA
C        NA        NA     North
C        NA        NA     East

我希望组合数据框看起来像这样。

ID      REGION
A        North    
A        South     
B        East      
B        West      
C        North       
C        East     

使用上一篇文章within(df, x3 <- ifelse(is.na(x1), x2, x1))works中的技术获取数字,但似乎没有很好地处理这些因素。

r merge r-factor
2个回答
2
投票

你需要使用levels。有关更多信息,请查看?factor的帮助文件。

within(df, x3 <- ifelse(is.na(x1), levels(x2)[x2], levels(x1)[x1]))

或者用你的例子:

within(df, x3 <- ifelse(!is.na(REGIONA), 
                        levels(REGIONA)[REGIONA], 
                        ifelse(!is.na(REGIONB), 
                               levels(REGIONB)[REGIONB],
                               levels(REGIONC)[REGIONC])))

2
投票
 # Reproducing your data frame:

 DF <- data.frame(ID=rep(c('A', 'B', 'C'), each=2), 
                  REGIONA=c('North', 'South', rep('NA', 4) ),
                  REGIONB=c('NA', 'NA', 'East', 'West', 'NA', 'NA'),
                  REGIONC=c(rep('NA', 4), 'North', 'East'))

 # Your data frame contains levels, it is necessary that 'NA' becomes NA, so:

 DF[DF=='NA'] <- NA

 # Removing NA's
 ind <- apply(DF, 2, is.na)
 new <- data.frame(matrix(DF[!ind], nrow(DF)))
 colnames(new) <- c('ID', 'REGION')
 new
  ID REGION
1  A  North
2  A  South
3  B   East
4  B   West
5  C  North
6  C   East
© www.soinside.com 2019 - 2024. All rights reserved.