R:合并相同变量的副本 [英] R: merging copies of the same variable
本文介绍了R:合并相同变量的副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在R中有这样的数据:
I have data like this in R:
subjID = c(1,2,3,4)
var1 = c(3,8,NA,6)
var1.copy = c(NA,NA,5,NA)
fake = data.frame(subjID = subjID, var1 = var1, var1 = var1.copy)
看起来像这样:
> fake
subjID var1 var1.1
1 1 3 NA
2 2 8 NA
3 3 NA 5
4 4 6 NA
Var1和Var1.1表示相同的变量,因此每个主题的一列具有NA,而另一列则具有数值(没有人具有两个NA或两个数字).我想合并这些列以获得单个Var1:(3、8、5、6).
Var1 and Var1.1 represent the same variable, so each subject has NA for one column and a numerical value in the other (no one has two NAs or two numbers). I want to merge the columns to get a single Var1: (3, 8, 5, 6).
有关如何执行此操作的任何提示?
Any tips on how to do this?
推荐答案
您可以使用is.na,它可以向量化为:
You can use is.na, which can be vectorised as:
# get all the ones we can from var1
var.merged = var1;
# which ones are available in var1.copy but not in var1?
ind = is.na(var1) & !is.na(var1.copy);
# use those to fill in the blanks
var.merged[ind] = var1.copy[ind];
这篇关于R:合并相同变量的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文