> -----Original Message-----
> From: r-help-boun...@r-project.org [mailto:r-help-bounces@r-
> project.org] On Behalf Of Zhenjiang Lan
> Sent: Tuesday, June 12, 2012 8:28 AM
> To: r-help@r-project.org
> Subject: [R] How to index a matrix with different row-number for each
> column?
> 
> here's my question: suppose I have a matrix:
> 
>     mt<-matrix(1:12,ncol=6)
> 
> now I have a vector
> 
>     vt<-c(1,2,2,2,1,2)
> 
> which means I want to get:
> the 1st row for column1;
> the 2nd row for column2;
> the 2nd row for column3;
> the 2nd row for column4;
> ...
> 
> that what I want is this vector:
> 1,4,6,8,9,12
> 
> Does anyone know how to do this fast?
> I know I can use for-loop to travel all columns,but that's not what I
> want.
> 

There may be a more memory efficient method, but this will get the job done.

diag(mt[vt,1:6])


Hope this is helpful,

Dan

Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA 98504-5204


______________________________________________
R-help@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.

Reply via email to