[R] Remove a number from a vector

William Dunlap wdunlap at tibco.com
Fri May 11 16:54:28 CEST 2012


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Berend Hasselman
> Sent: Friday, May 11, 2012 4:21 AM
> To: dkkhireche
> Cc: r-help at r-project.org
> Subject: Re: [R] Remove a number from a vector
> 
> 
> On 11-05-2012, at 12:45, dkkhireche wrote:
> 
> > Example :
> > *x=c("abba","bobo","cocoa")*
> > In order to remove "bobo" from *x* you need to do the following:
> > *x=x[which(x=="bobo")]*
> >
> 
> No. That does the opposite of what you describe.
> You do
> 
> x <- x[-which(x=="bobo")]
> 
> or better
> 
> x <- x[which(x!="bobo")]

The latter is better because it works when there is no
"bobo" in x:
   > xx <- c("cocoa", "dodo")
   > xx[-which(xx=="bobo")]
   character(0)
   > xx[which(xx!="bobo")]
   [1] "cocoa" "dodo"
You can also leave out the which and read the "[" as "such that": 
   > xx[xx!="bobo"] # xx such that xx is not "bobo"
  [1] "cocoa" "dodo"
That can give surprises when there are NA's in the data - it shows
you the NA's because it doesn't know if the missing value is "bobo"
or not:
   > xxx <- c("bobo", "cocoa", NA)
   > xxx[xxx!="bobo"]
   [1] "cocoa" NA
which(condition) uses the idiom
   !is.na(condition) & condition
to filter out FALSE's and NA's from condition.
     
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> 
> Berend
> 
> 
> > In case you already know the index of the element you want to get rid of, it
> > is even easier
> > *x=x[-elem.index]*
> >
> > Good luck
> >
> >
> >
> >
> > --
> > View this message in context: http://r.789695.n4.nabble.com/Remove-a-number-
> from-a-vector-tp851865p4626053.html
> > Sent from the R help mailing list archive at Nabble.com.
> >
> > ______________________________________________
> > 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.
> 
> ______________________________________________
> 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.



More information about the R-help mailing list