0

I was curious about computation time in R especially while dealing with matrix or data frame. Let's notice the following example:

    slowFun = function() {
      mat = as.data.frame(matrix(rnorm(10000 * 10), 10000, 10))
      mat[, (ncol(mat) + 1)] = NA
      for (i in 1:nrow(mat)) {
        mat[i,ncol(mat)] = sum(mat[i,], na.rm = T)
      }
    }

    fastFun = function() {
      mat = as.data.frame(matrix(rnorm(10000 * 10), 10000, 10))
      mat[, (ncol(mat) + 1)] = NA
      mat[,ncol(mat)] = rowSums(mat, na.rm = T)
    }


    system.time(slowFun())
    system.time(fastFun())

   > system.time(slowFun())
   user  system elapsed 
   3.614   0.219   3.837 
   > system.time(fastFun())
   user  system elapsed 
   0.012   0.001   0.013 

rowSums was impressive. When I tried to learn all about it:

    rowSums

It does not let me see how it was coded! I see .Internal and don't know where to look about it.
Any help will be appreciated.

overwhelmed
  • 225
  • 3
  • 12
  • 3
    This question is in the arena of the wider topic of vectorization in R. Of which you will find many discussions around. Here's one explanation: http://www.noamross.net/blog/2014/4/16/vectorization-in-r--why.html, especially part four on functions. – Pierre L Sep 29 '15 at 02:53
  • 3
    http://stackoverflow.com/questions/14035506/how-to-see-the-source-code-of-r-internal-or-primitive-function/14035586#14035586 – Ben Bolker Sep 29 '15 at 02:58
  • 3
    How to view the code for an `.Internal` function is described in the answer to [How can I view the source code for a function?](http://stackoverflow.com/q/19226816/271616). – Joshua Ulrich Sep 29 '15 at 02:59
  • http://cran.r-project.org/doc/Rnews/Rnews_2006-4.pdf – IRTFM Sep 29 '15 at 04:23
  • The reason is that the function was written in c++. If you are astounded by the speed of rowSums you should definitely try using Rfast's implementation (i.e. Rfast::rowsums) – Stefanos Oct 10 '18 at 23:31

0 Answers0