简体   繁体   English

结合r中的两个变量

[英]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 . 我有两个变量: varAvarB

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'将返回NAvarBNA 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM