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(): rmultinom(n=1,size=10,prob=(1:10)/10) # [,1] # [1,] 1 # [2,] 0 # [3,] 2 # [4,] 0 # [5,] 1 # [6,] 1 # [7,] 2 # [8,] 0 # [9,] 1 #[10,] 2 rmultinom(n=1,size=10,prob=(1:10)/10) # [,1] # [1,] 0 # [2,] 0 # [3,] 0 # [4,] 0 # [5,] 1 # [6,] 1 # [7,] 2 # [8,] 1 # [9,] 2 #[10,] 3 This gives each integer in (0:10) equal chances of being in the sample. For unequal chances, vary 'prob'. Hoping this helps, Ted. -------------------------------------------------------------------- E-Mail: (Ted Harding) <ted.hard...@wlandres.net> Fax-to-email: +44 (0)870 094 0861 Date: 08-Nov-11 Time: 00:25:54 ------------------------------ 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.