在 R 中将两列合并为一列 [英] Merging two columns into one in R
本文介绍了在 R 中将两列合并为一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据框,我正在尝试将两列合并为一列,同时将 NA
替换为数值.
I have the following data frame, and am trying to merge the two columns into one, while replacing NA
's with the numeric values.
ID A B
1 3 NA
2 NA 2
3 NA 4
4 1 NA
我想要的结果是:
ID New
1 3
2 2
3 4
4 1
提前致谢!
推荐答案
这在写答案时可能不存在,但由于我带着同样的问题来到这里并找到了更好的解决方案,这里是为未来的 googlers 准备的:
This probably didn't exist when the answers were written, but since I came here with the same question and found a better solution, here it is for future googlers:
你想要的是 dplyr
中的 coalesce()
函数:
What you want is the coalesce()
function from dplyr
:
y <- c(1, 2, NA, NA, 5)
z <- c(NA, NA, 3, 4, 5)
coalesce(y, z)
[1] 1 2 3 4 5
这篇关于在 R 中将两列合并为一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文