回复 第12楼 的 Davidhust:下面的代码,参考了吧里一些大神给的思路,由于2楼的大神代码的x是随机的,为了让大家看得更清楚,我在有些关键地方,显示出了一些变量的值,因而使得代码略长:
R>x <- matrix(0,5 ,10)<br />
R> x[sample(50, 20)] <- sample(50, 20)<br />
R> colnames(x) <- as.character(seq(as.Date("2010/1/1"), as.Date("2010/1/10"), "day"))<br />
R>x<br />
2010-01-01 2010-01-02 2010-01-03 2010-01-04 2010-01-05 2010-01-06<br />
[1,] 27 19 0 0 35 0<br />
[2,] 0 0 26 0 0 0<br />
[3,] 0 23 41 5 0 0<br />
[4,] 0 44 21 0 0 0<br />
[5,] 0 0 9 6 10 0<br />
2010-01-07 2010-01-08 2010-01-09 2010-01-10<br />
[1,] 37 1 0 0<br />
[2,] 49 0 0 12<br />
[3,] 43 24 0 46<br />
[4,] 0 0 0 0<br />
[5,] 31 0 0 0<br />
R> col <- apply(x, 1, function(x) which(x>0)[1] )<br />
R>col<br />
[1] 1 3 2 2 3<br />
R>col1=col+1;col2=col+2;col3=col+3;col4=col+4;col5=col+5;col6=col+6;<br />
R>dt=cbind(col,col1,col2,col3,col4,col5,col6)<br />
R>dt<br />
col col1 col2 col3 col4 col5 col6<br />
[1,] 1 2 3 4 5 6 7<br />
[2,] 3 4 5 6 7 8 9<br />
[3,] 2 3 4 5 6 7 8<br />
[4,] 2 3 4 5 6 7 8<br />
[5,] 3 4 5 6 7 8 9<br />
R>b=rep(1:nrow(dt),each=ncol(dt))<br />
R>d=cbind(b,as.numeric(t(dt)))<br />
R>d<br />
b<br />
[1,] 1 1<br />
[2,] 1 2<br />
[3,] 1 3<br />
[4,] 1 4<br />
[5,] 1 5<br />
[6,] 1 6<br />
[7,] 1 7<br />
[8,] 2 3<br />
[9,] 2 4<br />
[10,] 2 5<br />
[11,] 2 6<br />
[12,] 2 7<br />
[13,] 2 8<br />
[14,] 2 9<br />
[15,] 3 2<br />
[16,] 3 3<br />
[17,] 3 4<br />
[18,] 3 5<br />
[19,] 3 6<br />
[20,] 3 7<br />
[21,] 3 8<br />
[22,] 4 2<br />
[23,] 4 3<br />
[24,] 4 4<br />
[25,] 4 5<br />
[26,] 4 6<br />
[27,] 4 7<br />
[28,] 4 8<br />
[29,] 5 3<br />
[30,] 5 4<br />
[31,] 5 5<br />
[32,] 5 6<br />
[33,] 5 7<br />
[34,] 5 8<br />
[35,] 5 9<br />
R>dta=matrix(x[d],nrow(dt),byrow=TRUE)<br />
R>dta<br />
[,1] [,2] [,3] [,4] [,5] [,6] [,7]<br />
[1,] 27 19 0 0 35 0 37<br />
[2,] 26 0 0 0 49 0 0<br />
[3,] 23 41 5 0 0 43 24<br />
[4,] 44 21 0 0 0 0 0<br />
[5,] 9 6 10 0 31 0 0<br />
R>sum1=apply(dta,MARGIN=1,FUN=sum)<br />
R>sum1<br />
[1] 118 75 136 65 56<br />
R>
</p>