All, I've devised a way to toss a coin three times and record the number of heads, then use the table command to summarize the number of time 0, 1, 2, or 3 heads were obtained. n <- 100 x <- sample(c("H","T"),3*n,replace=TRUE) dim(x) <- c(3,n) num_heads <- apply(x,2,function(x) sum(x=="H")) table(num_heads)/n What I'd like to do next is run this code 10 times, and gather the results in a matrix with 10 rows and 4 columns, where the first row records the output of the first run of the above code, the second row records the second run of the above code, etc. Looking for some simple ideas on how to accomplish this. Thanks. David
On Tue, Oct 9, 2012 at 6:04 AM, David Arnold <dwarnold45 at suddenlink.net> wrote:> All, > > I've devised a way to toss a coin three times and record the number of heads, then use the table command to summarize the number of time 0, 1, 2, or 3 heads were obtained. > > n <- 100 > x <- sample(c("H","T"),3*n,replace=TRUE) > dim(x) <- c(3,n) > num_heads <- apply(x,2,function(x) sum(x=="H")) > table(num_heads)/n > > What I'd like to do next is run this code 10 times, and gather the results in a matrix with 10 rows and 4 columns, where the first row records the output of the first run of the above code, the second row records the second run of the above code, etc. > > Looking for some simple ideas on how to accomplish this. > > Thanks. > > DavidHi David, This is that wonderful smell of homework in the morning, so I can't really say too much in good conscience, but I think you are looking for ?replicate Cheers, Michael
Hello, Try the following. fun <- function(n = 100){ x <- sample(c("H","T"),3*n,replace=TRUE) dim(x) <- c(3,n) num_heads <- apply(x,2,function(x) sum(x=="H")) table(num_heads)/n } Runs <- 1e1 t(replicate(Runs, fun())) Hope this helps, Rui Barradas Em 09-10-2012 06:04, David Arnold escreveu:> All, > > I've devised a way to toss a coin three times and record the number of heads, then use the table command to summarize the number of time 0, 1, 2, or 3 heads were obtained. > > n <- 100 > x <- sample(c("H","T"),3*n,replace=TRUE) > dim(x) <- c(3,n) > num_heads <- apply(x,2,function(x) sum(x=="H")) > table(num_heads)/n > > What I'd like to do next is run this code 10 times, and gather the results in a matrix with 10 rows and 4 columns, where the first row records the output of the first run of the above code, the second row records the second run of the above code, etc. > > Looking for some simple ideas on how to accomplish this. > > Thanks. > > David > ______________________________________________ > 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.