[Yet another correction -- this one is important. I start from scratch this time]
On 07-Nov-11 22:22:54, SarahJoyes wrote: > Hey everyone, > I am at best, an amateur user of R, but I am stuck on how > to set-up the following situation. > I am trying to select a random sample of numbers from 0 to 10 > and insert them into the first column of a matrix (which will > used later in a loop). > However, I need to have those numbers add up to 10. How can > I set those conditions? > So far I have: > n<-matrix(0,nr=5,ncol=10) > for(i in 1:10){n[i,1]<-sample(0:10,1)} > How do I set-up the "BUT sum(n[i,1])=10"? > Thanks > SarahJ Sarah, your example is confusing because you have set up a matrix 'n' with 5 rows and 10 columns. But your loop cycles through 10 rows! However, assuming that your basic requirement is to sample 10 integers which add up to 10, consider rmultinom(): ### Instead of: rmultinom(n=1,size=10,prob=(1:10)/10) ### rmultinom(n=1,size=10,prob=rep(1,10)/10) # [,1] # [1,] 1 # [2,] 0 # [3,] 2 # [4,] 3 # [5,] 1 # [6,] 1 # [7,] 0 # [8,] 0 # [9,] 1 #[10,] 1 rmultinom(n=1,size=10,prob=rep(1,10)/10) # [,1] # [1,] 2 # [2,] 0 # [3,] 1 # [4,] 1 # [5,] 2 # [6,] 2 # [7,] 1 # [8,] 0 # [9,] 1 #[10,] 0 This gives a uniform distribution over the positions in the sample vector for the sampled integers, so that all permutations are equally likely. For a non-uniform distribution, vary 'prob'. Ted. -------------------------------------------------------------------- E-Mail: (Ted Harding) <ted.hard...@wlandres.net> Fax-to-email: +44 (0)870 094 0861 Date: 08-Nov-11 Time: 08:13:36 ------------------------------ XFMail ------------------------------ ______________________________________________ R-help@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.