Andrew Barr
2008-Sep-09 01:55 UTC
[R] isolate elements in vector that match one of many possible values
Hi all, I want to get the index numbers of all elements of a vector which match any of a long series of possible values. Say x <- c(1,2,3,4) and I want to know which values are equal to 1, 2 or 4. I could do which(x == 1 | x==2 | x==4) [1] 1 2 4 This gets really ugly though, when the list of values of interest is really long. Is there a nicer way to do this? Something akin to the MySQL construction in(), as in #MySQL script example Select * from table where parameter in(x,y,z); Thanks! -- W. Andrew Barr Biological Anthropology University of Texas at Austin [[alternative HTML version deleted]]
Rolf Turner
2008-Sep-09 02:11 UTC
[R] isolate elements in vector that match one of many possible values
On 9/09/2008, at 1:55 PM, Andrew Barr wrote:> Hi all, > > I want to get the index numbers of all elements of a vector which > match any > of a long series of possible values. Say x <- c(1,2,3,4) and I > want to know > which values are equal to 1, 2 or 4. I could do > > which(x == 1 | x==2 | x==4) > [1] 1 2 4 > > This gets really ugly though, when the list of values of interest > is really > long. Is there a nicer way to do this?which(x%in%c(1,2,4)) cheers, Rolf Turner ###################################################################### Attention:\ This e-mail message is privileged and confid...{{dropped:9}}
Adam D. I. Kramer
2008-Sep-09 06:54 UTC
[R] isolate elements in vector that match one of many possible values
Check out ?match, ?"%in%"> x <- c(1,2,3,4) > y <- c(1,2,4) > match(y,x)[1] 1 2 4>--Adam On Mon, 8 Sep 2008, Andrew Barr wrote:> Hi all, > > I want to get the index numbers of all elements of a vector which match any > of a long series of possible values. Say x <- c(1,2,3,4) and I want to know > which values are equal to 1, 2 or 4. I could do > > which(x == 1 | x==2 | x==4) > [1] 1 2 4 > > This gets really ugly though, when the list of values of interest is really > long. Is there a nicer way to do this? Something akin to the MySQL > construction in(), as in > > #MySQL script example > Select * from table where parameter in(x,y,z); > > Thanks! > > -- > W. Andrew Barr > Biological Anthropology > University of Texas at Austin > > [[alternative HTML version deleted]] > > ______________________________________________ > 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. >