[R] ifelse() and missing values in test conditions

Hosack, Michael mhosack at state.pa.us
Tue Jul 20 18:41:49 CEST 2010


R experts,

I have been unable to get the following ifelse statement to work as desired when applied 
to my data frame.

Example:

DF$ANYEF <- with(DF,ifelse(PSOUGHT1=='ANY'|PSOUGHT2=='ANY'|PSOUGHT3=='ANY',PEFF,0))
  
##### this statement will be replicated 16 times for 16 unique _EF variables ###

Basically, I want each ANYEF for each row to equal the corresponding row value for column 
PEFF if 'ANY' occurs at least once among columns PSOUGHT1, PSOUGHT2, and PSOUGHT3, and I want 
ANYEF to equal 0 if 'ANY' is not present within either PSOUGHT1 or PSOUGHT2 or PSOUGHT3. My 
ifelse statement will yield NAs rather than zeroes as desired whenever 'ANY' is not present 
and NAs are included in at least one of the PSOUGHT variables. This data frame is a small subset 
of a larger data frame.

Thank you,

Mike


DF <-
structure(list(SITE = c("EAST.AVE", "LAMPE", "LAMPE", "EAST.AVE", 
"EAST.AVE"), MM = c(5L, 5L, 5L, 9L, 9L), DD = c(19L, 23L, 23L, 
13L, 13L), PEFF = c(11.25, 9, 8, 1.5, 8), PSOUGHT1 = c("ANY", 
"SMB", "SMB", "YP", "ANY"), PSOUGHT2 = c("LMB", NA, NA, NA, NA
), PSOUGHT3 = c(NA, NA, NA, NA, NA), ANYEF = c(11.25, NA, NA, 
NA, 8)), .Names = c("SITE", "MM", "DD", "PEFF", "PSOUGHT1", "PSOUGHT2", 
"PSOUGHT3", "ANYEF"), class = "data.frame", row.names = c(24L, 
38L, 39L, 471L, 472L))



More information about the R-help mailing list