mardi 18 juillet 2017

Using ifelse statement in R dataframe to generate additional variables

I've got a dataframe in R with the following possible combinations in the first two columns:

 V1| V2| V3| V4
---|---|---|---
 0 | 0 | NA| NA
---|---|---|---
 0 | 1 | NA| NA
---|---|---|---
 0 | 2 | NA| NA
---|---|---|---
 1 | 0 | NA| NA
---|---|---|---
 1 | 1 | NA| NA
---|---|---|---
 1 | 2 | NA| NA
---|---|---|---
 2 | 0 | NA| NA
---|---|---|---
 2 | 1 | NA| NA
---|---|---|---
 2 | 2 | NA| NA

I would like to generate two ifelse statements or one if possible, so that I can get these two additional columns based on the different combinations:

 V1| V2| V3| V4
---|---|---|---
 0 | 0 | 0 | AA
---|---|---|---
 0 | 1 | 1 | AD
---|---|---|---
 0 | 2 | 2 | DD
---|---|---|---
 1 | 0 | 0 | AB
---|---|---|---
 1 | 1 | NA| NA
---|---|---|---
 1 | 2 | 1 | CD
---|---|---|---
 2 | 0 | 0 | BB
---|---|---|---
 2 | 1 | 0 | BC
---|---|---|---
 2 | 2 | 0 | CC

I'm really stuck at this point and none of the options I have tried work.

If I try something like this:

DF$V3 <- if((DF$V1=2) & (DF$V2 = 2)) {DF$V3 = 0}

All values in V1 and V2 are converted into 2 and all values in V3 are converted to 0.

If I use the elseif command in the following way:

DF$V3 <- elseif((DF$V1=2) & (DF$V2 = 2)) {DF$V3 = 0}

I get Error: could not find function "elseif"

I have read several forums about nested if and elseif statements in R, but I'm not able to figure out how to get the results I want using two conditions on two different columns.

Can somebody suggest any options?

Thank you very much,

Best,

Yatrosin

Aucun commentaire:

Enregistrer un commentaire