Skip to content
Prev 377791 / 398502 Next

R code for if-then-do code blocks

I got another 10% savings with this example by using only one
subscripting adjustment.
I also fixed a typo in my previous posting (which didn't affect the timing).



microbenchmark(
 rmh={
    d3 <-data.frame(ID=rownames(d1),
               d1,
               test1=0,
               test2=0,
               test4=0,
               test5=0)
    myRowSubset <- d3$gender=="f" & d3$workshop==1
    test1 <- 1
    d3[myRowSubset, "test1"] <- test1 + 6
    d3[myRowSubset, "test2"] <- test1 + 6 + 2
    d3[myRowSubset, c("test4", "test5")] <- test1
  },
 rmh4={
   d4 <- data.frame(ID=rownames(d1),
                    d1,
                    test1=0,
                    test2=0,
                    test4=0,
                    test5=0)
   myRowSubset <- d4$gender=="f" & d4$workshop==1
   test1 <- 1
   d4[myRowSubset, c("test1", "test2", "test4", "test5")] <-
     matrix(test1 + c(6, 6+2, 0, 0), nrow=sum(myRowSubset), ncol=4, byrow=TRUE)
 }
)

Unit: microseconds
 expr     min       lq     mean   median       uq      max neval cld
  rmh 956.187 1183.304 1538.012 1617.985 1865.149 2177.071   100   b
 rmh4 850.729 1042.997 1380.842 1416.476 1700.307 2448.545   100  a
On Mon, Dec 17, 2018 at 12:49 PM Richard M. Heiberger <rmh at temple.edu> wrote: