我想將2列中的值合并為1列。例如,以下是示例數據:
id x y
1 12
1 14
2 13
3 15
3 18
4 19
I want
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)
但是,該變量不反映連接的列。我是否錯誤地使用了此功能?
您可以使用
dplyr::coalesce
函數:要實現我自己的
mycoalesce
:And: