Re: [R] extracting rows from dataframe that match a vector

From: Gabor Csardi <csardi_at_rmki.kfki.hu>
Date: Tue, 5 Feb 2008 16:53:50 +0100

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

______________________________________________
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.
Received on Tue 05 Feb 2008 - 16:01:54 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 05 Feb 2008 - 16:30:11 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive