Skip to content
Prev 383551 / 398502 Next

how to create a new column from two columns with conditions

Hello,

Inline.

?s 22:44 de 29/04/20, Ana Marija escreveu:
Yes, that's it. If b$FLASER == 2 | b$PLASER == 2 returns TRUE then 
adding 1 will give

TRUE + 1 -> 1 + 1 -> 2

This is because logical values are internally coded as integers 0 and 1.
And if the condition returns FALSE it becomes

FALSE + 1 -> 0 + 1 -> 1

In both cases the result is what you want.
What I write above is valid even if your data contains NA's, like it 
does. This is because

(TRUE | x) == (x | TRUE) == TRUE

even if x is NA.

This is an example with some NA values in the data.

set.seed(1234)
b <- rbind(b, b)
i <- sample(nrow(b), 3)
b$FLASER[i] <- NA
i <- sample(nrow(b), 2)
b$PLASER[i] <- NA
b$PLASER[10] <- 2

b$PHENO <- (b$FLASER == 2 | b$PLASER == 2) + 1
b


As you can see,

row 5:

b$FLASER is NA, b$PLASER == 2 evaluates to TRUE -> b$PHENO is TRUE

row 10:

b$FLASER == 2 evaluates to TRUE, b$PLASER is NA -> b$PHENO is TRUE


So the code is not broken by NA's

Hope this helps,

Rui Barradas