[R] extracting rows from dataframe that match a vector

Gabor Csardi csardi at rmki.kfki.hu
Tue Feb 5 16:53:50 CET 2008


You almost got it right. THe solution is

df[df$ind %in% subgr,]

See ?"%in%"

G.

On Tue, Feb 05, 2008 at 04:47:02PM +0100, Karin Lagesen wrote:
> 
> Hi!
> 
> I have a large dataframe that I want to extract a subset from. This
> subset has a certain column value that matches elements in a vector I
> have defined. So, my question is how do I get the rows that match one
> of the elements in the vector.
> 
> Example:
> 
> a = c(1:5)
> b = letters[1:10]
> df = data.frame(ind = a, letrs = b)
> 
> > df
>    ind letrs
> 1    1     a
> 2    2     b
> 3    3     c
> 4    4     d
> 5    5     e
> 6    1     f
> 7    2     g
> 8    3     h
> 9    4     i
> 10   5     j
> >
> 
> 
> # Now I want to extract all of the rows where ind == 2, 4 or 5.
> # This would be rows 2, 4, 5, 7, 9 and 10 
> 
> subgr = c(2,4,6)
> 
> My most natural inclination would be to do 
> 
> df[df$ind == subgr,]
> 
> However, this does not work:
> 
> 
> > df[df$ind == subgr,]
>   ind letrs
> 7   2     g
> Warning message:
> In df$ind == subgr :
>   longer object length is not a multiple of shorter object length
> >
> 
> So, which part of this is it that I have misunderstood?
> 
> Thanks for your help btw!
> 
> Karin
> -- 
> Karin Lagesen, PhD student
> karin.lagesen at medisin.uio.no
> http://folk.uio.no/karinlag
> 
> ______________________________________________
> 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.

-- 
Csardi Gabor <csardi at rmki.kfki.hu>    UNIL DGM



More information about the R-help mailing list