[R] Issue with a function

peter dalgaard pdalgd at gmail.com
Tue Sep 30 09:38:16 CEST 2014

On 30 Sep 2014, at 03:47 , Jeff Newmiller <jdnewmil at dcn.davis.ca.us> wrote:

> library(Matrix)
> result <- newX %*% Diagonal( unlist(beta) )

The code in Matrix does this efficiently, I hope?

Otherwise, sweep() is the traditional ticket:

result <- sweep(newX, 2, unlist(beta), "*")

Some of my students do

t(t(newX) * unlist(beta))

(utilizing recycling of beta) which I think looks horrible, but it does work. 

The problem with the original code is that the cbind() reallocates storage every time a column is added to the result. This can be alleviated by preallocating. Also note that the double for loop in

for (i in 1: ncol(newX)){
 for (j in 1: length(beta)){
   Terms <- cbind (Terms,(newX[,i]*beta[j]))

generates 520*520 columns of pairwise products, which I presume was not the intention.

Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com

More information about the R-help mailing list