[R] function in R that's equivalent to SQL's "IN"
ggrothendieck at gmail.com
Fri Oct 26 23:21:28 CEST 2007
Here are a few ways:
with(z, y[x %in% w])
subset(z, x %in% w)$y
z[z$x %in% w, "y"]
z$y[z$x %in% w]
# see sqldf.googlecode.com for more info
sqldf("select y from z where x in (2, 3, 5)")
# but if you know that x is 1:n and the components of w are in
# that set, as is the case in the example, then the above reduce to
# any of these
On 10/26/07, Em C <mmmraspberries at hotmail.com> wrote:
> Hi all,
> I'm trying to find
> something like the "==" operator that will work on vectors or something
> equivalent to SQL's "IN" function. For e.g., if I have:
> x <- c(1,2,3,4,5)
> y <- c("apples", "oranges", "grapes", "bananas", "pears")
> z <- data.frame (x,y)
> w <- c(2,4,5)
> I want R to return the values "oranges", "bananas", "pears" through some function like this:
> z$y[z$x == w]
> or in sql speak, like this
> z$y[z$x IN w]
> To complicate matters, my x variable is a date variable (as is w). Essentially, I have a bunch of dates with associated values and I want to retrieve all the associated values for particular dates.
> Is there any R function that will do this in a one-line, non-messy way? Thanks very much for any help!
> [[alternative HTML version deleted]]
> 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