2
\$\begingroup\$

I have written some code to calculate effects using the Delta method.

I have a dataframe dpcp with variables x1, x2, x3, x4 and a matrix of 1000 draws from a multivariate normal, m4[1000,4].

This code works to calculate the effects, but it runs very slowly - it currently takes upwards of 5 hours for only 2000 observations. How can I improve the runtime?

n=nrow(dpcp)
for (i in 1:n)

 {

     for (j in 1:1000)
      {        
     marg_effects[i,j]=(m4[j,1]*dpcp[i,]$x1)+(m4[j,2]*dpcp[i,]$x2)+(m4[j,3]*dpcp[i,]$x3)+(m4[j,4]*dpcp[i,]$x4)          
 } 
   } 
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Please edit your post to try and fix the formatting of your code (selecting it all and pressing ctrl+k would be a good start). Use the preview window to ensure the code as displayed matches the way it looks in your editor. This will give reviewers the best chance of understanding your code. \$\endgroup\$
    – forsvarir
    Commented Jul 15, 2016 at 15:40

1 Answer 1

2
\$\begingroup\$

Aren't you looking for a simple matrix multiplication? Try:

x <- as.matrix(dpcp[c("x1", "x2", "x3", "x4")])

Then

marg_effects <- x %*% t(m4)

or equivalently (maybe a little faster):

marg_effects <- tcrossprod(x, m4)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.