Search code examples
rmatrixdplyrmatrix-multiplication

Matrix multiplication of each row in data frame


This should be elementary, but cannot get my head around it. I have a data frame and want to create a new variable as the matrix multiplication of each row by a pre-specified vector.


library(dplyr)
data <- data.frame(matrix(1:6,2))
vector <- c(1,0,1)

##NOT WORKING
data <- data %>%
mutate(multiplication = as.numeric(data[,]) %*% vector)

mm <- function(x,y){
  n <- as.numeric(x)
  m <- n %*% y
  print(as.numeric(m))
}

##NOT WORKING
data$mm <- lapply(data[,], function(x) mm(x,vector))


Solution

  • You can use apply:

    data %>% mutate(multiplication = apply(., 1, function(x) x %*% vector))
    #>   X1 X2 X3 multiplication
    #> 1  1  3  5              6
    #> 2  2  4  6              8