Wei Shung
Wei Shung

Reputation: 93

How to get the sum of the product of selected column in a data frame?

This is probably very simple but I couldn't think of a solution. I have the following data frame, and I want to multiply column y with column z and sum the answer.

> df <- data.frame(x = c(1,2,3), y = c(2,4,6), z = c(2,3,4))
> df
  x y z
1 1 2 2
2 2 4 3
3 3 6 4

The value found should be equal to 40.

Upvotes: 1

Views: 29

Answers (2)

at80
at80

Reputation: 780

Additionally, you could use data table. The second row after the comma indicates columns (j). You don't need the spaces, they're just there to show how it works.

library(data.table)

a <- data.table(x = c(1,2,3), y = c(2,4,6), z = c(2,3,4))
#dt i    j      by
a[   , sum(y*z),  ]

Upvotes: 0

akrun
akrun

Reputation: 887128

with would be an option here if we don't want to repeat df$ or df[[ to extract the column

with(df, sum( y * z))
#[1] 40

Or %*%

c(df$y %*% df$z)

Upvotes: 1

Related Questions