Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matrix multiplication from the data frame in R

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

"%*%" 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading