> -----Original Message----- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] > On Behalf Of SarahJoyes > Sent: Monday, November 07, 2011 2:23 PM > To: r-help@r-project.org > Subject: [R] Sampling with conditions > > 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, Does something like this do what you want? n <- matrix(0,nrow=5, ncol=10) repeat{ c1 <- sample(0:10, 4, replace=TRUE) if(sum(c1) <= 10) break } n[,1] <- c(c1,10-sum(c1)) n Hope this is helpful, Dan Daniel Nordlund Bothell, WA USA ______________________________________________ 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.