1

I think I need you help.

I have a table like this:

Product   Price   Quantity   Quality
1          10       100         100
2          15      1200          88
1          12        88          95

Now, I want to calculate the average mean per product dependent of the Quantity. I have no trouble doing that in Excel, but I don't know how i should solve this problem in R.

If I use something like this:

weighted.mean(Test_weighted_avg$Price, Test_weighted_avg$Quantity, group_by=Product)

the "group_by" function don't work and I don't know, how I can add a second variable. :/

Is there someone who can help me?

jazzurro
  • 23,179
  • 35
  • 66
  • 76
Torte
  • 13
  • 4

1 Answers1

2

As far as I know, weighted mean does not take a group_by argument. To calculate the weighted mean per group, you could try:

df = read.table(text='Product   Price   Quantity   Quality
    1          10       100         100
                2          15      1200          88
                1          12        88          95',header=T)

library(dplyr)    
df %>% group_by(Product) %>% summarize(wm = weighted.mean(Price, Quantity))

Output:

# A tibble: 2 x 2
  Product       wm
    <int>    <dbl>
1       1 10.93617
2       2 15.00000

Hope this helps!

Florian
  • 24,425
  • 4
  • 49
  • 80