[R] How do you test if a number is in a list of numbers?

Bill.Venables at csiro.au Bill.Venables at csiro.au
Sun Oct 11 09:43:40 CEST 2009

This is pretty standard.

varList <- 1:4
subData <- subset(dataset, var %in% varList)

Should do it.

From: r-help-bounces at r-project.org [r-help-bounces at r-project.org] On Behalf Of JustinNabble [justinmmcgrath at hotmail.com]
Sent: 11 October 2009 16:13
To: r-help at r-project.org
Subject: [R]  How do you test if a number is in a list of numbers?

I want to subset a data frame if one of the variables matches any in a list.
I could of course do something like this:
subset(dataset, var == 1 | var == 2 | var ==3)
but that's tedious.

I tried
varlist = c(1,2,3,4)
subset(dataset, any(var == varlist))
but it doesn't work because 'any' doesn't go row-by-row and hence always
returns TRUE.

Is there any simple way to do this?

View this message in context: http://www.nabble.com/How-do-you-test-if-a-number-is-in-a-list-of-numbers--tp25840964p25840964.html
Sent from the R help mailing list archive at Nabble.com.

R-help at r-project.org mailing list
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