Skip to content
Prev 302353 / 398506 Next

Head or Tails game

Hi,

system.time({
set.seed(111)
colSums(matrix(sample(c(-1, 1), 40*10000, TRUE), ncol = 10000))
})
user? system elapsed 
? 0.032?? 0.012?? 0.041?

system.time({
?set.seed(112)
?list1<-vector("list",10000)
?for(i in 1:10000){
? list1[[i]]<-sample(c(-1,1),40,replace=TRUE)}
? dat1<-do.call(rbind,lapply(list1,function(x) sum(x)))
?dat2<-matrix(dat1,ncol=200,byrow=TRUE)
?})
?? user? system elapsed 
? 0.112?? 0.000?? 0.111?
#modified version

system.time({
?set.seed(112)
?list1<-vector("list",10000)
?for(i in 1:10000){
? list1[[i]]<-sample(c(-1,1),40,replace=TRUE)}
? dat1<-unlist(lapply(list1,function(x) sum(x)))
? })
?user? system elapsed 
?0.092?? 0.000?? 0.092 


It seems like Michael's solution is better in terms of the CPU utilization.? I guess, the loop created the difference.

A.K.



----- Original Message -----
From: Michael Weylandt <michael.weylandt at gmail.com>
To: darnold <dwarnold45 at suddenlink.net>
Cc: "r-help at r-project.org" <r-help at r-project.org>
Sent: Friday, August 3, 2012 10:20 PM
Subject: Re: [R] Head or Tails game
On Aug 3, 2012, at 9:14 PM, darnold <dwarnold45 at suddenlink.net> wrote:

            
colSums(matrix(sample(c(-1, 1), 40*10000, TRUE), ncol = 10000))

or some such

Michael
______________________________________________
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.