Odp: NA-values and logical operation
Hi Patrick Hausmann <Patrick.Hausmann at uni-bremen.de> napsal dne 13.01.2009 18:18:38:
Hi Petr, works perfect, thanks a lot! Perhaps you can take a look at this 'problem'? I want to get a new vector for which (x == 2 & y == 2 & z == 2) = TRUE (the real dataframe has 21 columns to check) o <- data.frame(x=c(2,2,2,2,2), y=c(1,2,2,2,NA), z=c(2,NA,2,1,2)) #> o == 2 # x y z #[1,] TRUE FALSE TRUE #[2,] TRUE TRUE NA #[3,] TRUE TRUE TRUE #[4,] TRUE TRUE FALSE #[5,] TRUE NA TRUE apply(o == 2 , 1, function(x) isTRUE(x)) # [1] FALSE FALSE FALSE FALSE FALSE At least I would expect the third index to be TRUE...
Not so. See help page for isTRUE isTRUE(x) is an abbreviation of identical(TRUE, x), and so is true if and only if x is a length-one logical vector with no attributes (not even names). ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ which is not your case I would use all
apply(o == 2 , 1, function(x) all(x))
[1] FALSE NA TRUE FALSE NA or check rowSums
rowSums(o==2)
[1] 2 NA 3 2 NA
rowSums(o==2, na.rm=T)
[1] 2 2 3 2 2 Depending what rows you want to have true. Regards Petr
Best Patrick Zitat von Petr PIKAL <petr.pikal at precheza.cz>:
Hi r-help-bounces at r-project.org napsal dne 13.01.2009 11:58:45:
Dear list,
as a result of a logical operation I want to assign
a new variable to a DF with NA-values.
z <- data.frame( x = c(5,6,5,NA,7,5,4,NA),
y = c(1,2,2,2,2,2,2,2) )
p <- (z$x <= 5) & (z$y == 1)
p
z[p, "p1"] <-5
z
# ok, this works fine
z <- z[,-3]
p <- (z$x <= 5) & (z$y == 2)
p
z[p, "p2"] <-5
z
# this failed... - how can I assign the value '5' to the new
# var "p2"
z[which(p), "p2"] <-5 works. Regards Petr
Thanks for any help!! Patrick
______________________________________________ R-help at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.