[R] how to use "apply" function partial to each vector of a matrix
zhaoxing731
zhaoxing731 at yahoo.com.cn
Tue Jan 11 06:17:20 CET 2011
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
I just want to use the "apply" function to the matrix partially
there is a vector end=c(2,3,1,3)
#sum the 1st 2 numbers of the 1st column
#sum the 1st 3 numbers of the 2nd column
#sum the 1st number of the 3rd column
#sum the 1st 3 numbers of the 4th column
#they are specified by vector end
a for loop
for (i in 1:4)
{
outsum=sum[1:end[i],i]
}
but when I want to do it to a large dataset, it's inefficency becomes a problem, so need vectorization
the "apply" function will sum all of each vector, which is not my purpose
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
__________________________________________________
¸Ï¿ì×¢²áÑÅ»¢³¬´óÈÝÁ¿Ãâ·ÑÓÊÏä?
More information about the R-help
mailing list