"NA-friendly" operator
Instead of ignore-NA versions of ">", "<", "==", etc., I prefer to factor out the ignore-NA part of things: is.true <- function(x) !is.na(x) & x is.false <- function(x) !is.na(x) & !x used as > is.false(c(1,2,NA,4) > 3) [1] TRUE TRUE FALSE FALSE > is.true(c(1,2,NA,4) > 3) [1] FALSE FALSE FALSE TRUE or with any other expression that evaluates to a logical. subset() must have a similar thing buried in it and people use it for that but then get caught up in its nonstandard evaluation semantics. which() must also have it but you don't always want to convert to integer indexes. Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com
-----Original Message----- From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Berend Hasselman Sent: Tuesday, October 30, 2012 2:26 PM To: vincent guyader Cc: r-help at r-project.org Subject: Re: [R] "NA-friendly" operator 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
______________________________________________ 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.