[R] vectorisation

arun smartpink111 at yahoo.com
Sat Feb 2 23:08:38 CET 2013


Hi,

Not sure this helps:

ml <- data.frame(matrix(sample(1:50,80, replace=TRUE),20,4))
mm <- apply(ml, 2, cumsum)
starts<- data.frame(matrix(0,600,4))
starts1<- data.frame(matrix(0,600,4))
for (i in 1:4){
starts1[,i][mm[,i]] <-1
}

starts2<-as.data.frame(do.call(cbind,lapply(1:4,function(i) {starts[,i][mm[,i]]<-1;starts[,i]})))
colnames(starts2)<- colnames(starts1)
identical(starts1,starts2)
#[1] TRUE

#loop should be fast compared to lapply
ml <- data.frame(matrix(sample(1:1e4,1e3, replace=TRUE),100,4))
mm <- apply(ml, 2, cumsum)
starts<- data.frame(matrix(0,1e6,4))
starts1<- data.frame(matrix(0,1e6,4))
system.time({for (i in 1:4){
starts1[,i][mm[,i]] <-1
}})
 #user  system elapsed 
  # 0.63    0.30    0.92 
system.time(starts2<-as.data.frame(do.call(cbind,lapply(1:4,function(i) {starts[,i][mm[,i]]<-1;starts[,i]}))))

# user  system elapsed 
 #  0.74    0.26    1.03 

colnames(starts2)<- colnames(starts1)
identical(starts1,starts2)
#[1] TRUE
A.K.



----- Original Message -----
From: Brett Robinson <brett.robinson at 7dials.com>
To: "r-help at r-project.org" <r-help at r-project.org>
Cc: 
Sent: Saturday, February 2, 2013 11:38 AM
Subject: [R] vectorisation

Hi
I'm trying to set up a simulation problem without resorting to (m)any loops. I want to set entries in a data frame of zeros ('starts' in the code below) to 1 at certain points and the points have been randomly generated and stored in a separate data.frame ('sl'), which has the same number of columns.

An example of the procedure is as follows:
ml <- data.frame(matrix(sample(1:50,80, replace=TRUE),20,4))
mm <- apply(ml, 2, cumsum)
starts<- data.frame(matrix(0,600,4))

I can achieve the result I want with a loop:
for (i in 1:4){
lstarts[,i][mm[,i]] <-1
}

But as I want to use a large number of columns I would like to do away with the loop

Can anyone suggest how this might be done?

Thanks in advance

Brett Robinson

______________________________________________________________________
This email has been scanned by the Symantec Email Security.cloud service.
For more information please visit http://www.symanteccloud.com
______________________________________________________________________
    [[alternative HTML version deleted]]

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




More information about the R-help mailing list