title: Apply a function to each row of a matrix without using lapply function in R
body: <p>I have a input data frame with multiple rows. For each row, I want to apply a function. The input data frame has 1,000,000+ rows. How can I speed up the part using <code>lapply</code>  ? I would like to avoid the apply family of functions as in <a href="https://stackoverflow.com/questions/24684057/efficient-way-to-apply-function-to-each-row-of-data-frame-and-return-list-of-dat">Efficient way to apply function to each row of data frame and return list of data frames</a> because these methods seem to be slow in my case. </p>
  
  <p>Here is a reproducible example with a simple function:</p>
  
  <pre><code>library(tictoc)   # enable use of tic() and toc() to record time taken for test to compute
  
  func &lt;- function(coord, a, b, c){
  
    X1 &lt;- as.vector(coord[1])
    Y1 &lt;- as.vector(coord[2])
    X2 &lt;- as.vector(coord[3])
    Y2 &lt;- as.vector(coord[4])
  
    if(c == 0) {
  
      res1 &lt;- mean(c((X1 - a) : (X1 - 1), (Y1 + 1) : (Y1 + 40)))
      res2 &lt;- mean(c((X2 - a) : (X2 - 1), (Y2 + 1) : (Y2 + 40)))
      res &lt;- matrix(c(res1, res2), ncol=2, nrow=1)
  
    } else {
  
      res1 &lt;- mean(c((X1 - a) : (X1 - 1), (Y1 + 1) : (Y1 + 40)))*b
      res2 &lt;- mean(c((X2 - a) : (X2 - 1), (Y2 + 1) : (Y2 + 40)))*b
      res &lt;- matrix(c(res1, res2), ncol=2, nrow=1)
  
    }
  
    return(res)
  }
  
  ## Apply the function
  set.seed(1)
  n = 10000000
  tab &lt;- as.matrix(data.frame(x1 = sample(1:100, n, replace = T), y1 = sample(1:100, n, replace = T), x2 = sample(1:100, n, replace = T), y2 = sample(1:100, n, replace = T)))
  
  
  tic("test 1")
  test &lt;- do.call("rbind", lapply(split(tab, 1:nrow(tab)),
                                  function(x) func(coord = x,
                                                   a = 40,
                                                   b = 5,
                                                   c = 1)))
  toc()
  
  
  
   ## test 1: 453.76 sec elapsed
  </code></pre>