[R] Create a vector of indices from a matrix of start and end points

George W. Gilchrist gwgilc at wm.edu
Sat Sep 23 14:44:44 CEST 2006


I have a very large dataframe and wish to extract a subset of rows. I  
have a two column matrix listing the starting and ending indices of  
one subset on each row. My idea is to create a vector of indices that  
could be applied to the dataframe and I have a solution using a for  
loop (below). But surely there is some more elegant way to do this! I  
looked thorough the archives without success. Thanks for any ideas.

 > tmp1 <- matrix(c(2,5,7,9,15,20), 3,2, byrow=T)
 > tmp1
      [,1] [,2]
[1,]    2    5
[2,]    7    9
[3,]   15   20
 > t.ind <- NULL
 > for (i in 1:3) t.ind <- c(t.ind, seq(tmp1[i,1], tmp1[i,2]))
 > t.ind
[1]  2  3  4  5  7  8  9 15 16 17 18 19 20
 >

cheers, George

..................................................................
George W. Gilchrist                           Email: gwgilc at wm.edu
Director of Graduate Studies                 Phone: (757) 221-7751
Department of Biology, Box 8795                Fax: (757) 221-6483
College of William & Mary
Williamsburg, VA 23187-8795
http://gwgilc.people.wm.edu/



More information about the R-help mailing list