[R] extracting rows from dataframe that match a vector
Karin Lagesen
karin.lagesen at medisin.uio.no
Tue Feb 5 16:47:02 CET 2008
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
More information about the R-help
mailing list