0

I'm studying matrix multiplication in R. I want to do matrix multiplication from the data frame. Let's say I have df and beta as follows:

df <- data.frame(one = c(1,1,1,1,1),
                 x1=c(21,34,24,35,42),
                 x2=c(32,24,13,21,35))
beta<-c(1,2,2)

df is a 5 by 3 matrix and beta is 3 by 1 matrix. I want to multiply beta to df to get a 5 by 1 column matrix. Usually, using the standard multiplication, the code should be

df%*%beta 

I want to do this multiplication and also give it a column name df_beta. But since there are variable names on each column, this matrix multiplication doesn't work. How to do this?

Lee
  • 369
  • 1
  • 6

1 Answers1

2

"%*%" has no "data.frame" method. This is reasonable because there is no guarantee that all columns in a data frame are numeric.

To get a result, you need as.matrix(df) %*% beta. But you take full responsibility to ensure the type conversion gives correct result (watch out for potential character matrix, for which I had a discussion here: Matrix multiplication in R: requires numeric/complex matrix/vector arguments).

Once it executes correctly, to store the result in a new column, use

df$df_beta <- c(as.matrix(df) %*% beta)
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248