[R] extracting rows from dataframe that match a vector

From: Karin Lagesen <karin.lagesen_at_medisin.uio.no>
Date: Tue, 05 Feb 2008 16:47:02 +0100

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.
Received on Tue 05 Feb 2008 - 15:49:27 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