[英]Combining two variables in r
I think this is a super easy question, but I can't seem to figure it out. 我认为这是一个非常容易的问题,但我似乎无法弄清楚。
I have two variables: varA
and varB
. 我有两个变量: varA
和varB
。
varA
has values 'a'
and NA
, and varB has values 'b'
and NA
. varA
值为'a'
和NA
,而varB的值为'b'
和NA
。
I want to combine them into one variable varC
with value 'a'
where varA
is =='a'
and 'b'
where varB
is =='b'
. 我想将它们组合为一个变量varC
,值'a'
其中varA
是=='a'
而值'b'
是varB
是=='b'
。
I have tried this: 我已经试过了:
varC <- varA
varC[varB=='b'] <- varB
but I get the error: 但是我得到了错误:
Error in [<-.factor(tmp, varB == "b", : NAs are not allowed in subscripted assignments [<-。factor(tmp,varB ==“ b”,中的错误::下标分配中不允许使用NA
What am I doing wrong here? 我在这里做错了什么?
The condition varB=='b'
will return NA
when varB
is NA
. 条件varB=='b'
将返回NA
时varB
是NA
。 Use is.na()
to test for NA
. 使用is.na()
测试NA
。 Here is an example: 这是一个例子:
a <- c(NA, 'a', NA)
b <- c('b', NA, 'b')
c <- a
c[is.na(c)] <- b[is.na(c)]
c
[1] "b" "a" "b"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.