使用 coalesce 将 2 列合并为 1 的问题

problem with using coalesce to merge 2 columns into 1

我想将 2 列的值合并为 1 列。例如,这里是示例数据:

id   x    y
1   12  
1         14  
2   13      
3   15 
3         18
4         19

我要

id   x    y     z
1   12          12  
1         14    14  
2   13          13 
3   15          15 
3         18    18
4         19    19

我尝试使用 coalesce 创建一个新变量。

coalesce <- function(...) {
  apply(cbind(...), 1, function(x) {
    x[which(!is.na(x))[1]]
  })
}

df$z <- coalesce(df$x, df$y)

但是,变量不反映连接的列。我是不是用错了这个功能?

如果 xy 之一总是 NA 并且其中一个有价值,

自定义函数 %+% 定义为

`%+%` <- function(x, y)  mapply(sum, x, y, MoreArgs = list(na.rm = TRUE))

df$z <- df$x %+% df$y
df
  id  x  y  z
1  1 12 NA 12
2  1 NA 14 14
3  2 13 NA 13
4  3 15 NA 15
5  3 NA 18 18
6  4 NA 19 19

您可以使用 dplyr::coalesce 函数:

> df$z <- dplyr::coalesce(ifelse(df$x == "", NA, df$x), df$y)
> df
  id  x  y  z
1  1 12    12
2  1    14 14
3  2 13    13
4  3 15    15
5  3    18 18
6  4    19 19
> 

实现我自己的mycoalesce:

mycoalesce <- function(...) {apply(cbind(...), 1, max)}

并且:

> df$z <- mycoalesce(df$x, df$y)
> df
  id  x  y  z
1  1 12    12
2  1    14 14
3  2 13    13
4  3 15    15
5  3    18 18
6  4    19 19
> 

这可能比上面发布的其他方法更粗糙、效率更低,但仍然值得一试:

df1<-df
df1[is.na(df1)]=0
z=df1$x+df1$y
df<-cbind(df,z)
df
#  ID  x  y  z
#1  1 12 NA 12
#2  2 NA 14 14
#3  3 13 NA 13
#4  4 15 NA 15
#5  5 NA 18 18
#6  6 NA 19 19

我主要是把原来的dataframe复制到一个新的dataframe中,以便保留原来dataframe中的NA值。另外,我假设 ID 中的 none 与@Park 的假设一起丢失了。

数据:df<-data.frame(ID=1:6,x=c(12,NA,13,15,NA,NA),y=c(NA,14,NA,NA,18,19))