将两列合并为R中的一列 [英] Merging two columns into one in R

查看:106
本文介绍了将两列合并为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

提前谢谢!

推荐答案

撰写答案时可能不存在,但是由于我来这里时遇到的是相同的问题,并且找到了更好的解决方案,因此这是给将来的Google员工使用的:

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()函数:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆