0

I have a table e.g.

Example table

I need the total cost when Number, PetName, PetColour, OwnerName are the the same. for example, when its (123, John, Brown, George) i.e. the first two rows, so total cost for the first two columns would be 37 (25+12). For the third row, the number is differnt to the its not added to the 37

Thanks Very Much!!!

user9445536
  • 141
  • 1
  • 1
  • 9
  • [See here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on making an R question that folks can help with. That includes a sample of data, all necessary code, and a clear explanation of what you're trying to do and what hasn't worked. – camille Nov 18 '19 at 22:27

1 Answers1

2

We can use ave in base R to create the sum grouped by the columns of interest

df1$TotalCost <- with(df1, ave(Cost, Number, PetName PetColour,
                OwnerName, FUN = sum))

Or in dplyr

library(dplyr)
df1 %>%
  group_by(Number, PetName, PetColour, OwnerName) %>%
  mutate(TotalCost = sum(Cost))
akrun
  • 874,273
  • 37
  • 540
  • 662