[datatable-help] Sum first 3 non zero elements of row
jim holtman
jholtman at gmail.com
Tue May 21 20:55:45 CEST 2013
Is this what you want:
> x <- matrix(sample(c(0,1), 200, TRUE, prob = c(10,1)), ncol = 20)
> # sum up to at most first 3 non-zero items
> xSum <- apply(x, 1, function(.row){
+ indx <- which(.row != 0)[1:3]
+ return(sum(.row[indx], na.rm = TRUE))
+ })
> xSum
[1] 0 0 1 2 2 2 3 2 3 2
> cbind(apply(x, 1, paste, collapse = ''))
[,1]
[1,] "00000000000000000000"
[2,] "00000000000000000000"
[3,] "10000000000000000000"
[4,] "00000000001000000001"
[5,] "00001000001000000000"
[6,] "01001000000000000000"
[7,] "01001000000000000100"
[8,] "00000010000001000000"
[9,] "00100100000001000000"
[10,] "00000001000000010000"
>
On Tue, May 21, 2013 at 5:10 AM, JNV <jose at memo2.nl> wrote:
> Hi there,
> I've got this matrix D with, say 10 rows and 20 columns. For each row I
> want
> to sum the first 3 non zero elements and put them in a vector z.
>
> So if the first row D[1,] is
> 0 3 5 0 8 9 3 2 4 0
>
> then I want z
> z<-D[1,2]+D[1,3]+D[1,5]
>
> But if there are less than 3 non zero elements, those should be summed. If
> there are no non zero elements, the result must be zero.
>
> So if the first row D[1,] is
> 0 0 3 0 1 0 0 0 0 0
>
> then I want z
> z<-D[1,3]+D[1,5]
>
> Hope someone can help me out!
>
>
>
> --
> View this message in context:
> http://r.789695.n4.nabble.com/Sum-first-3-non-zero-elements-of-row-tp4667563.html
> Sent from the datatable-help mailing list archive at Nabble.com.
> _______________________________________________
> datatable-help mailing list
> datatable-help at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/datatable-help
>
--
Jim Holtman
Data Munger Guru
What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/datatable-help/attachments/20130521/5e88c54b/attachment.html>
More information about the datatable-help
mailing list