[R] Sampling with conditions

Daniel Nordlund djnordlund at frontier.com
Tue Nov 8 00:56:50 CET 2011

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
> On Behalf Of SarahJoyes
> Sent: Monday, November 07, 2011 2:23 PM
> To: r-help at 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


Does something like this do what you want?

n <- matrix(0,nrow=5, ncol=10)
  c1 <- sample(0:10, 4, replace=TRUE)
  if(sum(c1) <= 10) break
n[,1] <- c(c1,10-sum(c1))

Hope this is helpful,


Daniel Nordlund
Bothell, WA USA

More information about the R-help mailing list