Skip to content
Prev 304090 / 398513 Next

ifelse problem - bug or operator error

Hello,

Michael's standard guess, FAQ 7.31, was also mine, but is wrong. The 
error is in Jennifer's flag column,  not the result of her ifelse. (!)


x <- scan(what="character", text="
  PM.EXP PM.DIST.TOT PM.DIST_flag  0 0 0  0 0 0  0 0 0  177502 1 0 31403 1
0  0 0 0  1100549 1 0  38762 1 0  0 0 0  20025 1 0  0 0 0  13742 1 0  0 0 0
83078 1 0  0 0 0  0 0 0  0 0 0  0 0 0  0 0 0  0 0 0  0 0 0  0 0 0  0 0 0
165114 1 0  0 0 0  417313 1 0  3546 1 0  4613 1 0  225460 1 0  6417 1 1  23
1 0  3402 1 0  8504 1 1  8552 1 0  9723 1 0  37273 1 1  396 1 0 1478 1 0
2074 1 0  12220 1 1  97691 2 1  0 0 0  33993 2 1
")

vn <- matrix(as.numeric(x[-(1:3)]), ncol=3, byrow=TRUE)
vn <- data.frame(vn)
names(vn) <- x[1:3]
str(vn)
vn$flag2 <- ifelse( (vn$PM.EXP > 0.0) & (vn$PM.DIST.TOT != 1.0), 1, 0 )

str(vn)
identical(vn$PM.DIST_flag, vn$flag2)  # FALSE
inx <- vn$PM.DIST_flag != vn$flag2
vn[inx, ]

As you can see, there's nothing wrong with ifelse. The second standard 
guess is that Jennifer had something, a variable, in her session messing 
up with the variables envolved in the ifelse.

Also, when the result of a if/else or ifelse is, by this order, 1 or 0, 
the following can be used, with performance benefits.

vn$flag3 <- 1 * (vn$PM.EXP > 0.0 & vn$PM.DIST.TOT != 1.0) # make T/F 
numeric 1/0

Hope this helps,

Rui Barradas
Em 24-08-2012 21:43, Jennifer Sabatier escreveu: