Message-ID: <750026E9-97E1-4FB1-B255-139CA48C8BCC@xs4all.nl>
Date: 2012-10-30T21:25:30Z
From: Berend Hasselman
Subject: "NA-friendly" operator
In-Reply-To: <CANCN_HT2KmRzz0tNzxzqkSL6T3RJUMt8ouckY_baN03FA+ag8Q@mail.gmail.com>
On 30-10-2012, at 22:08, vincent guyader wrote:
> Hi everyone,
>
> i'm looking for a "NA-friendly" operator
>
> I explain :
>
> vec<-c(3,4,5,NA,1,NA,9,NA,1)
>
> vec[vec == 1] # NA 1 NA NA 1
>
> I dont want the NA's :
> vec[vec == 1 & ! is.na(vec)]# 1 1
> is the same as
> vec[vec %in% 1] # 1 1
>
> %in% is NA-friendly :)
>
> But if i want >2 without the NA's :
>
> vec[vec>2] #3 4 5 NA NA 9 NA
>
> if i dont want the NA i have to do :
>
> vec[vec>2 & !is.na(vec)] #3 4 5 9
>
> is there an op?rator to directly do that?
You could define one
"%>.nona%" <- function(x,y) x[x>y & !is.na(vec)]
and use
vec %>.nona% 2
Use ?`%in%` to see an example (in the Examples section)
Berend