[R] row sum question

jim holtman jholtman at gmail.com
Mon Dec 22 13:52:12 CET 2008


Will this do it for you:

> nrows <- 10
> ncols <- 10
> mat <- matrix(sample(0:1, nrows * ncols, TRUE), nrow=nrows, ncol=ncols)
> mat
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1    0    1    1    1    0    0    0    0     0
 [2,]    0    0    0    0    0    0    0    1    1     0
 [3,]    0    1    0    0    1    1    1    1    1     1
 [4,]    0    1    1    1    0    0    0    0    1     1
 [5,]    0    0    1    0    1    1    1    0    0     0
 [6,]    1    0    1    0    0    0    1    0    0     0
 [7,]    0    0    1    0    0    1    0    0    1     1
 [8,]    1    0    1    0    0    0    1    1    1     0
 [9,]    0    1    0    1    0    1    1    0    0     0
[10,]    0    1    1    1    1    0    0    0    1     0
> mask <- rep(1, ncols)
> for (i in 1:nrows){
+     print(sum(mask & mat[i,]))
+     mask <- mask & !mat[i,]
+ }
[1] 4
[1] 2
[1] 4
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0


On Sun, Dec 21, 2008 at 8:36 PM, Keun-Hyung Choi <khchoi at sfsu.edu> wrote:
> Dear helpers,
>
>
>
> I'm using R version 2.8.0.
>
> Suppose that I have a small data set like below.
>
> [,1] [,2] [,3] [,4]
>
> a    1    1    0    0
>
> b    0    1    1    0
>
> c    1    1    1    0
>
> d    0    1    1    1
>
>
>
> First, I'd like to find row sum of values uniquely present in each row, but
> only sequentially from the top row, meaning that if the value is shown in
> the above row(s) already, the same value in the following row shouldn't be
> added into the sum.
>
> The result should be like this:
>
>
>
> row.sum
>
> [1] 2 1 0 1
>
>
>
> And if a and c were swapped, the row.sum is  3 0 0 1
>
>
>
> Second, I'd like to randomly reorder the rows, and repeat calculating
> row.sum again, for many times less than all combinations possible (4! In
> this case), kind of simulation, and store the results into a matrix.
>
> Thanks.
>
> Keun-Hyung
>
>
>
>
>
>
>
>
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?



More information about the R-help mailing list