Reputation: 31
I am just learning R, and trying to play around with indexing to help me understand. But, I try this code, and don't get what I expect:
> x
[1] 3 6 1 NA 2
> x[!is.na(x[x>2])]
[1] 3 6 NA 2
Shouldn't the results of the second command be those elements of x
that are not NA
and are GT 2
? In other words, it should return 3 6
. What am I not understanding about this?
Upvotes: 0
Views: 119
Reputation: 6365
This should do what you want:
x[!is.na(x) & x > 2]
Your command
x[!is.na(x[x>2])]
first returns all the x[x>2]
, which is
3 6 NA
!is.na(c(3, 6, NA))
TRUE TRUE FALSE
So x[!is.na(x[x>2])]
has the effect of dropping the third element of x.
Upvotes: 3
Reputation: 3082
As
> !is.na(x[x>2])
[1] TRUE TRUE FALSE
While the length of your vector is 5 Therefore it will give
[1] TRUE TRUE FALSE TRUE TRUE
Thus, x[c(1,2,4,5)]
are returns
My approach will be
>x <- x[!is.na(s)]
>x[x>2]
[1] 3 6
I am still thinking whether one line code is able to do the task.
Okay @6pool have provide a better answer
x[!is.na(x) & x > 2]
Upvotes: 1