合并具有NA值的列

时间:2017-03-10 00:59:38

标签: r merge

有没有办法将columes与NA值合并?

例如

a <- data.frame(x1 = c("a", NA, NA), y1 = c(NA, "e1", NA), z1 = c("g", NA, "i"), x2 = c(NA, "b", NA), y2 = c("d", "e2", "f"), z2 = c(NA, "h", NA), x3 = c(NA, NA, "c"))

给出

    x1   y1   z1   x2 y2   z2   x3
1    a <NA>    g <NA>  d <NA> <NA>
2 <NA>   e1 <NA>    b e2    h <NA>
3 <NA> <NA>    i <NA>  f <NA>    c

所需的输出是

     x       y    z
1    a       d    g
2    b   e1 e2    h
3    c       f    i

2 个答案:

答案 0 :(得分:0)

您可以使用is.naifelseNA转换为空字符串,然后使用paste合并列,使用trimws删除前导和尾随空格:

a <- data.frame(x1 = c("a", NA, NA), y1 = c(NA, "e1", NA), z1 = c("g", NA, "i"), x2 = c(NA, "b", NA), y2 = c("d", "e2", "f"), z2 = c(NA, "h", NA), x3 = c(NA, NA, "c"), 
                stringsAsFactors = FALSE)
a2 <- lapply(a, function(x) ifelse(is.na(x),"",x))
data.frame(x=trimws(paste(a2$x1,a2$x2,a2$x3)),
                 y=trimws(paste(a2$y1,a2$y2)), 
                 z=trimws(paste(a2$z1,a2$z2)))
  x     y z
1 a     d g
2 b e1 e2 h
3 c     f i

答案 1 :(得分:0)

以下是使用dplyrreshape2的另一种方式:

library(reshape2)
library(dplyr)
melt(as.matrix(a)) %>%
  filter(!is.na(value)) %>%
  group_by(Var1, g=substr(Var2, 1, 1)) %>%
  summarise(value=paste(value, collapse=" ")) %>%
  dcast(Var1 ~ g, value.var="value") %>%
  select(-Var1)