Re: [R] subsetting data-frame by vector of characters

From: Chuck Cleland <ccleland_at_optonline.net>
Date: Fri, 13 Jun 2008 10:20:49 -0400

On 6/13/2008 10:07 AM, james perkins wrote:
> Hi,
>
> I have a very simple problem but I can't think how to solve it without
> using a for loop and creating a large logical vector. However given the
> nature of the problem I am sure there is a "1-liner" that could do the
> same thing much more efficiently.
>
> bascially I have a dataframe with characters in, eg
>
> >names.and.numbers
>
> (index) Name Fave.Number
> 1 John 7
> 2 Tony 12
> 3 Phil 14
> 4 Adam 22
> 5 Robert 23
>
>
> Now, imagine I have a vector of names, ie:
>
> >names = c("John,Phil,Robert")
>
> All I want to do is get the subset of the dataframe which corresponds to
> the names in the vector "Names". IE
>
> (index) Name Fave.Number
> 1 John 7
> 2 Phil 14
> 3 Robert 23
>

> Sorry, I know its trivial but I'm new to R and its hard to start
> thinking in R, as I say, I've written a complicated for loop using
> intersect and creating a logical table, but this is very long winded!!!

   How about this:

subset(names.and.numbers, Name %in% mynames)

   where mynames is the vector of names you want?

?subset

?is.element

> Regards,
>
> Jim
>
> ______________________________________________
> 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.

-- 
Chuck Cleland, Ph.D.
NDRI, Inc. (www.ndri.org)
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894

______________________________________________
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 Fri 13 Jun 2008 - 16:57:07 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 Fri 13 Jun 2008 - 17:30:39 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