[R] Finding elements in a character vector

From: Downey, Patrick <PDowney_at_urban.org>
Date: Fri, 08 Apr 2011 19:52:22 -0400


Hello,

I have two character vectors: list.a and list.b. Every element of list.a appears somewhere in list.b. Not all elements of list.b are in list.a, and some elements of list.b appear multiple times in list.a. I want to create a new vector (index) of the same length as list.a where the nth element of index is the location in list.b of the nth element of list.a.

This code will work, but I have heard over and over again that using loops is inefficient in R and that there are (almost always) better ways to do things.

for(i in 1:length(list.a)){
index[i] <- seq(1,length(list.b))[list.b==list.a[i]] }

Thank you,
Mitch



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 08 Apr 2011 - 23:55: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 Sat 09 Apr 2011 - 00:10:28 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