[R] dot products

Petr Savicky savicky at cs.cas.cz
Wed Mar 7 21:32:43 CET 2012


On Wed, Mar 07, 2012 at 03:14:05PM -0500, Alexander Shenkin wrote:
> Hello,
> 
> I need to take a dot product of each row of a dataframe and a vector.
> The number of columns will be dynamic.  The way I've been doing it so
> far is contorted.  Is there a better way?
> 
>     dotproduct <- function(dataf, v2) {
>         apply(t(t(as.matrix(a)) * v2),1,sum) #contorted!
>     }
> 
>     df = data.frame(a=c(1,2,3),b=c(4,5,6))
>     vec = c(4,5)
>     dotproduct(df, vec)

Hi.

If i understand correctly, then the following should
be equivalent

  as.matrix(df) %*% cbind(vec)

       [,1]
  [1,]   24
  [2,]   33
  [3,]   42

Hope this helps.

Petr Savicky.



More information about the R-help mailing list