<div><div dir="ltr">Thank you, it really helped me out! Didn't need the data.table like you proposed.<p></p></div></div>
<br><br><div class="gmail_quote">2013/5/21 Gabor Grothendieck <span dir="ltr"><<a href="mailto:ggrothendieck@gmail.com" target="_blank">ggrothendieck@gmail.com</a>></span><br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div class="im">On Tue, May 21, 2013 at 5:10 AM, JNV <<a href="mailto:jose@memo2.nl">jose@memo2.nl</a>> wrote:<br>
> Hi there,<br>
> I've got this matrix D with, say 10 rows and 20 columns. For each row I want<br>
> to sum the first 3 non zero elements and put them in a vector z.<br>
><br>
> So if the first row D[1,] is<br>
> 0 3 5 0 8 9 3 2 4 0<br>
><br>
> then I want z<br>
> z<-D[1,2]+D[1,3]+D[1,5]<br>
><br>
> But if there are less than 3 non zero elements, those should be summed. If<br>
> there are no non zero elements, the result must be zero.<br>
><br>
> So if the first row D[1,] is<br>
> 0 0 3 0 1 0 0 0 0 0<br>
><br>
> then I want z<br>
> z<-D[1,3]+D[1,5]<br>
><br>
<br>
</div>Here is a matrix, D, with those two rows The t(apply(...)) replaces<br>
the first non-zero element in each row with 1, the 2nd with 2, etc.<br>
(It puts garbage into the elements that are 0.) We then convert<br>
this to T/F according to whether each element less than or equal to 3<br>
or not and multiply by the original data which both zaps the garbage<br>
in the zero positions and zaps those positions which are a 4th or more<br>
non-zero in each row. This multiplication also inserts the correct<br>
values into the good positions. Finally we sum the rows using what is<br>
left:<br>
<br>
> D <- matrix( c(0, 0, 3, 0, 5, 3, 0, 0, 8, 1, 9, 0, 3,<br>
+ 0, 2, 0, 4, 0, 0, 0), 2)<br>
><br>
> D<br>
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]<br>
[1,] 0 3 5 0 8 9 3 2 4 0<br>
[2,] 0 0 3 0 1 0 0 0 0 0<br>
><br>
> as.data.table(D)[, rowSums((t(apply(.SD > 0, 1, cumsum)) <= 3) * .SD)]<br>
[1] 16 4<br>
<br>
Not sure if this really benefits from data.table as we could have<br>
written this without data.table:<br>
<br>
> rowSums((t(apply(D > 0, 1, cumsum)) <= 3) * D)<br>
[1] 16 4<br>
<br>
<br>
--<br>
Statistics & Software Consulting<br>
GKX Group, GKX Associates Inc.<br>
tel: 1-877-GKX-GROUP<br>
email: ggrothendieck at <a href="http://gmail.com" target="_blank">gmail.com</a><br>
</blockquote></div><br>