[R] Adding logical vectors
David Huffer
David.Huffer at csosa.gov
Thu Aug 13 21:21:36 CEST 2009
When adding several logical vectors I expect each vector will be
coerced to integers and these vectors will then be added.
That doesn't always seem to be the case.
For example:
> ( f1 <- as.factor ( sample ( "x" , 25 , rep = T ) ) )
[1] x x x x x x x x x x x x x x x x x x x x x x x x x
Levels: x
> ( f2 <- as.factor ( sample ( "y" , 25 , rep = T ) ) )
[1] y y y y y y y y y y y y y y y y y y y y y y y y y
Levels: y
> ( f3 <- as.factor ( sample ( "z" , 25 , rep = T ) ) )
[1] z z z z z z z z z z z z z z z z z z z z z z z z z
Levels: z
>
> is.na ( f1 [ sample ( 1:25 , 4 ) ] ) <-
+ is.na ( f2 [ sample ( 1:25 , 4 ) ] ) <-
+ is.na ( f3 [ sample ( 1:25 , 4 ) ] ) <- TRUE
>
> ## this returns a numeric vector:
>
> is.na ( f1 ) + is.na ( f2 ) + is.na ( f3 )
[1] 0 0 0 0 0 1 1 0 0 0 1 0 0 1 0 0 1 0 1 2 2 0 1 0 1
>
> ## but this returns a logical vector
>
> !is.na ( f1 ) + !is.na ( f2 ) + !is.na ( f3 )
[1] TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE
[9] TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE
[17] FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE
[25] FALSE
>
Can someone please explain why the returned value is a logical
vector when I use the not operator but a numeric vector when I
don't.
What is special about the !is.na? it returns an object of class
logical just like the is.na function:
> all.equal ( class ( !is.na ( f1 ) ) , class ( is.na ( f1 ) ) )
[1] TRUE
>
Thanks!
More information about the R-help
mailing list