与NA的[复制]合并列(Combine column with NA's [duplicat

2019-09-26 13:42发布

这个问题已经在这里有一个答案:

  • 合并列删除NA的 9个答案

我有一个数据帧

data <- data.frame('a' = c('A','B','C','D','E'),
              'x' = c(1,2,NA,NA,NA),
              'y' = c(NA,NA,3,NA,NA),
              'z' = c(NA,NA,NA,4,NA))

它看起来像这样:

  a  x  y  z
1 A  1 NA NA
2 B  2 NA NA
3 C NA  3 NA
4 D NA NA  4
5 E NA NA NA

我希望得到这样的数据:

  a  N
1 A  1
2 B  2
3 C  3
4 D  4
5 E NA

谢谢!

Answer 1:

使用A dplyr溶液coalesce

library(dplyr)

data %>%
    mutate(N = coalesce(x, y, z)) %>%
    select(a, N)

  a  N
1 A  1
2 B  2
3 C  3
4 D  4
5 E NA

无需selecttransmute

data %>%
    transmute(a, N = coalesce(x, y, z))


Answer 2:

你可能想尝试这样的事:

> result <- apply(data[, -1], 1, function(x) ifelse(all(is.na(x)), NA, x[!is.na(x)]))
> data.frame(a=data[,1], N=result)
  a  N
1 A  1
2 B  2
3 C  3
4 D  4
5 E NA


Answer 3:

pmax似乎本身在这里建议,这应该是基本的更快相比遍历各行大数据:

do.call(pmax, c(data[c("x","y","z")],na.rm=TRUE) )
#[1]  1  2  3  4 NA

cbind(data["a"], N=do.call(pmax, c(data[c("x","y","z")],na.rm=TRUE) ))
#  a  N
#1 A  1
#2 B  2
#3 C  3
#4 D  4
#5 E NA


文章来源: Combine column with NA's [duplicate]