MCS
MCS

Reputation: 1101

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))

Upvotes: 1

Views: 675

Answers (4)

akrun
akrun

Reputation: 887851

We can use crossprod from base R

data$multiplication <- crossprod(t(data), vector)[,1]

-output

data
#  X1 X2 X3 multiplication
#1  1  3  5              6
#2  2  4  6              8

Upvotes: 0

Yuriy Saraykin
Yuriy Saraykin

Reputation: 8880

use as.matrix


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

data %>%
  mutate(multiplication = as.matrix(data[,]) %*% vector)
#>   X1 X2 X3 multiplication
#> 1  1  3  5              6
#> 2  2  4  6              8

Created on 2020-12-11 by the reprex package (v0.3.0)

Upvotes: 0

tmfmnk
tmfmnk

Reputation: 40171

One option could be:

data %>%
 rowwise() %>%
 mutate(multiplication = sum(c_across(everything()) * vector))

     X1    X2    X3 multiplication
  <int> <int> <int>          <dbl>
1     1     3     5              6
2     2     4     6              8

Upvotes: 0

Allan Cameron
Allan Cameron

Reputation: 174476

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

Upvotes: 1

Related Questions