在R中合并两列 [英] Combine two columns in R

查看:118
本文介绍了在R中合并两列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何合并两列并替换R中的缺失值?

How do I combine two columns and replace missing values in R?

假设我有一个data.frame:

Let's say I have a data.frame:

D = data.frame(a = c(1,NA,3), b = c(1,2,NA))

看起来像这样

   a  b
1  1  1
2 NA  2
3  3 NA

如何使它看起来像这样:

How would I get it to look like this:

  c
1 1
2 2
3 3

推荐答案

假定两列的值相同或其中之一为NA

Assuming the two columns will either have the same values or one of them will be NA

D = data.frame(a = c(1,NA,3), b = c(1,2,NA))
D[['c']] <- rowMeans(D, na.rm = TRUE)
D

   a  b c
1  1  1 1
2 NA  2 2
3  3 NA 3

这篇关于在R中合并两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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