tobinz
tobinz

Reputation: 335

Matrix multiplication in tibble

I have a specific question about how to do matrix multiplication in a tibble.

The sample codes are:

suppose I havea tibble W with dimension: 100-by-10:

W <- as_tibble( x=matrix( rnorm(1000,0,2) ,nrow=100,ncol=10,dimnames = list(NULL,c("C1","C2","C3","C4","C5","C6","C7","C8","C9","C10" ) ))) 

and a known matrix R with dim(R) = 5 ,11.

I want to extract a 100-by-5 matrix from W and pre-multiply

R <- matrix(runif(55, 1,20), nrow = 5, ncol=11)

and

W_use <- as.matrix(W %>% select(C2,C4,C6,C8,C10))

Their product is

WR <- W_use %*% R

Since dim(WR)=(100,11), I can put it in the original tibble W by

W_total <- W %>% add_column(WR)

My concern is that though I can achieve this by a tedious process, it's proved to be slow, particularly the matrix multiplication.

Can we use some smart ways to circumvent the matrix construction and multiplication and get the same tibble W_total? Thanks.

Upvotes: 1

Views: 599

Answers (1)

akrun
akrun

Reputation: 887213

If we need to do this in a single chain

library(dplyr)
library(magrittr)
W1 <- W %>% 
      select(C2, C4, C6, C8, C10) %>%
      as.matrix %>%
      multiply_by_matrix(R) %>%
      as_tibble %>%
      bind_cols(W, .)

Or use crossprod

W %>% 
   select(C2, C4, C6, C8, C10) %>% 
   t %>% 
   crossprod(R) %>% 
   add_column(.)

Upvotes: 1

Related Questions