0

I have a dataframe with 2 columns:

Price . Category
10 . Cat-A
5 . Cat-B
20 . Cat-A
30 . Cat-A
15 . Cat-B

So, I have count = 3 for Cat-A and thus I need a new column which sums the price for Cat-A and divides by the count of category i.e., (10+20+30)/3 = 20

Final table should look like this:

Price . Category . Ratio
10 . Cat-A . 20
5 . Cat-B . 10
20 . Cat-A . 20
30 . Cat-A . 20
15 . Cat-B . 10
A_K
  • 1
  • 2

1 Answers1

0

Here's a way using base R assuming your dataframe is called df-

df$Ratio <- ave(df$Price, df$Category, FUN = mean)
Shree
  • 10,835
  • 1
  • 14
  • 36