[R] Making a point-sampling matrix

andrija djurovic djandrija at gmail.com
Sat Feb 4 16:45:04 CET 2012


Hi.
If I understood you correctly here is one approach to your solution:

> k <- 5
> mat <- diag(1,nrow=k,ncol=k)
> set.seed(10)
> samp <- mat[sample(1:k,3,rep=FALSE),]
> samp
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    1    0    0
[2,]    0    1    0    0    0
[3,]    0    0    0    1    0
> #check
> apply(samp,1,sum)
[1] 1 1 1
> apply(samp,2,sum)
[1] 0 1 1 1 0

I hope this helps
Andrija


On Sat, Feb 4, 2012 at 4:27 PM, Alaios <alaios at yahoo.com> wrote:
> Dear all,
> I would like to create a k,n matrix which that will include
>
>
>
> - k random elements with value 1
> -all rest zeros
>
> -one single "1" in each row
>
> - each column will have maximum one "1"
>
>
> so far I have a so stupid function that with nested while tries to fit k numbers randomly in a row by row fashion, checking also if the c column rule is violated. In that case there is also another loop that will try to find a new solution.
>
> That way it takes ages, as it is natural to complete a matrix of 300,512 as the new ones conflict all the time.
>
> I am trying to find an easy way to make this algorithm way simpler that will help me reduce the time needed.
> I was thinking then if R can help me by shuffling number from 1  to 300 randomly, so to avoid the first loop that does that goes row by row.. and then find an easy way to check if the column rule is violated.
>
> Do you think that you can spend some time help me?
>
> Have a nice weekend
>
> Regards
> Alex
>
>        [[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.
>



More information about the R-help mailing list