[R] Discarding a matrix based on the rowSums value
David Winsemius
dwinsemius at comcast.net
Mon Nov 21 18:13:43 CET 2011
On Nov 21, 2011, at 10:58 AM, Juan Antonio Balbuena wrote:
> Hello
> I would appreciate your help on the followig. I want to generate
> random
> binary matrices but I need to discard those with all-1 rows. That
> is, for a
> 10x10 matrix with five 1's
>
> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
> [1,] 0 0 0 0 0 0 0 0 0 1
> [2,] 0 0 0 0 0 0 1 0 0 0
> [3,] 0 0 0 0 0 0 1 0 0 0
> [4,] 0 0 0 0 0 0 0 0 0 0
> [5,] 0 0 0 0 0 0 0 0 0 0
> [6,] 0 0 0 0 0 0 0 0 0 0
> [7,] 0 0 0 0 0 0 0 0 0 0
> [8,] 0 0 0 0 0 0 0 0 0 0
> [9,] 0 0 0 0 0 0 0 0 0 0
> [10,] 0 0 0 0 0 1 1 0 0 0
>
> would be passed on to further computations, whereas
>
> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
> [1,] 0 0 0 0 0 0 0 0 0 0
> [2,] 0 0 0 0 0 0 0 0 0 0
> [3,] 0 0 0 0 0 0 0 0 0 0
> [4,] 0 0 0 0 0 0 0 0 0 0
> [5,] 0 0 0 0 0 0 0 0 0 0
> [6,] 0 0 0 0 0 0 0 0 0 0
> [7,] 0 0 0 0 0 0 0 0 0 0
> [8,] 0 0 0 0 0 0 0 0 0 0
> [9,] 0 0 0 0 0 0 0 0 0 0
> [10,] 0 1 0 1 0 1 1 0 0 1
> must be discarded.
Why? it has no rows that meet your verbal description " all-1
rows" (Nor it would meet your code implementation below, but I offer a
suggestion in case you want only to exclude matrices with exactly rows
whose sum is 5 but would accept those with sums of 4, or 6, etc.)
>
> For any N.1s <= Nrow, I am trying
>
> Nrow = 10
> Ncol = 10
> N.1s = 5
> flag <- TRUE
> while (flag == TRUE) {
> m <- matrix ((sample (c(rep(1, each=N.1s), rep(0,
> each=((Ncol*Nrow)-N.1s))))), Nrow)
> SUMROW <- rowSums(m)
> if (SUMROW == N.1s) {flag <- TRUE} else {flag <- FALSE}
rowSums retruns a vector, whereas if() only works with vectors of
length 1.
Perhaps you want:
flag <- ifelse(SUMROW == N.1s, TRUE, FALSE) #?
> }
> }
>
> but I get this warning
> Warning message:
> In if (SUMROW == N.1s) { :
> the condition has length > 1 and only the first element will be used
>
> What I specifically need is a way to write "If any of the elements
> of the
> SUMROW vector == N.1s then flag <-true else flag<-false".
>
> Any help would be much appreciated.
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Discarding-a-matrix-based-on-the-rowSums-value-tp4091995p4091995.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list