[R] how to coerce part of each column of a matrix to a vector and merge them

From: zhaoxing731 <zhaoxing731_at_yahoo.com.cn>
Date: Tue, 11 Jan 2011 13:32:35 +0800


Hello

Suppose I have a matrix mat=(1:16,2)

     [,1] [,2] [,3] [,4]

[1,]    1    5    9   13
[2,]    2    6   10   14
[3,]    3    7   11   15
[4,]    4    8   12   16

there is a vector end=c(2,3,1,3)

#coerce the 1st 2 numbers of the 1st column to a vector [1] 1 2
#coerce the 1st 3 numbers of the 2nd column and append it to the previous vector [1] 1 2 5 6 7
#coerce the 1st number of the 3rd column and append it to the previous vector [1] 1 2 5 6 7 9
#coerce the 1st 3 numbers of the 4th column and append it to the previous vector [1] 1 2 5 6 7 9 13 14 15
#they are specified by vector end

a for loop

mat<-matrix(1:16,4)
end<-c(2,3,1,3)
vec<-numeric()
for (i in 1:4)
	{vec<-c(vec,mat[1:end[i],i])
	}

#the result

 > vec
[1] 1 2 5 6 7 9 13 14 15

 but when I want to do it to a large dataset, it's inefficiency becomes a problem, so need vectorization

 Thank you in advance
 Yours sincerely

ZhaoXing
Department of Health Statistics
West China School of Public Health
Sichuan University
No.17 Section 3, South Renmin Road
Chengdu, Sichuan 610041
P.R.China



ϿעŻ?

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 Tue 11 Jan 2011 - 07:24:06 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 Tue 11 Jan 2011 - 10:30:06 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