1

I have a data frame as following:

 id     weight     value
231      50         0.6
231      50         0.43
420      30         0.86
420      30         0.12

How can I multiply all values per each id and weight to have the following table:

id     weight     value
231     50       0.6*0.43
420     30       0.86*0.12
user36729
  • 545
  • 5
  • 30
  • 1
    It's not clear exactly what you mean. Why not just `df$weight * df$value`? – Allan Cameron Mar 13 '20 at 15:54
  • @AllanCameron I made some edits in my question. – user36729 Mar 13 '20 at 16:01
  • There are a lot of SO posts on summary statistics by group, and you should be able to adapt them to use `prod` instead of functions like `sum`, `mean`, `min`, etc. See [here](https://stackoverflow.com/q/1660124/5325862), [here](https://stackoverflow.com/q/9847054/5325862), and [here](https://stackoverflow.com/q/52413271/5325862) for starters – camille Mar 13 '20 at 16:12

2 Answers2

2

Use prod() to multiply all the values in its arguments.

library(dplyr)

df %>%
  group_by(id, weight) %>%
  summarise(prod = prod(value))

# # A tibble: 2 x 3
# # Groups:   id [2]
#      id weight  prod
#   <int>  <int> <dbl>
# 1   231     50 0.258
# 2   420     30 0.103

Or a base way

aggregate(value ~ id + weight, df, prod)
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
0

With data.table

library(data.table)
setDT(df)[, .(Prod = prod(value)), .(id, weight)]
akrun
  • 874,273
  • 37
  • 540
  • 662