stevec
stevec

Reputation: 52268

Matrix multiplication on dataframe in R?

Is there an established/best practice way to matrix multiply a data.frame, as opposed to an object of strictly matrix class? That is, is there an alternative to or variation of %*% that happily accepts data.frames?

The sole purpose is to save the clutter of the extraneous code used to convert the data.frame to a matrix before providing it to %*%.

E.g. this

as.matrix(data.frame(a=c(1,2,3), b=c(5,6,7))) %*% c(2,2)

could simplify to

data.frame(a=c(1,2,3), b=c(5,6,7)) %*% c(2,2)

Upvotes: 0

Views: 1535

Answers (2)

stevec
stevec

Reputation: 52268

Matrix multiply data.frames like so

library(mmr)

x <- data.frame(a=c(1,2,3), b=c(5,6,7))
y <- c(2,2)


mm(x, y)
#   V1
# 1 12
# 2 16
# 3 20

x %mm% y
#   V1
# 1 12
# 2 16
# 3 20

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

You can use sweep to multiply the values in dataframe with vector and then use rowSums.

rowSums(sweep(data.frame(a=c(1,2,3), b=c(5,6,7)), 2, c(2, 2), `*`))
#[1] 12 16 20

Another method is to transpose the dataframe and multiply and then take colSums however, transposing converts dataframe to matrix.

colSums(t(data.frame(a=c(1,2,3), b=c(5,6,7))) * c(2, 2))

Upvotes: 1

Related Questions