I have a dataframe in r called house_expenses that looks like this (2 columns: DESCRIPTION and AMOUNT):
DESCRIPTION AMOUNT
----------- ---------
COUCH $801.713
TV $4999.996
TV_MOUNT $575.867
ENTERTAINMENT_SYSTEM $1102.392
MATTRESS $1225.893
BEDFRAME $356.789
PILLOWS $528.989
I would like to create two additional columns to the dataframe that has the sums and is rounded to 2 decimal places:
- LIVING_ROOM_COSTS = sum(round(COUCH, TV, TV_MOUNT, ENTERTAINMENT_SYSTEM), =2)
- BEDROOM_COSTS = sum(round(MATTRESS, BEDFRAME, PILLOWS), =2)
I have tried doing
house_expenses <- house_expenses %>%
group_by(DESCRIPTION) %>%
mutate(LIVING_ROOM_COSTS = sum(round(DESCRIPTION == "COUCH" &
DESCRIPTION == "TV" &
DESCRIPTION == "TV_MOUNT" &
DESCRIPTION == "ENTERTAINMENT_SYSTEM" , digits = 2)),
mutate(BEDROOM_COSTS = sum(round(DESCRIPTION == "MATTRESS" &
DESCRIPTION == "BEDFRAME" &
DESCRIPTION == "PILLOWS", digits = 2)))
But unfortunately this hasn't worked. Had anyone come across this before and know how to approach this problem?
To get the solution you want you have to do some subsetting,
Description %in% c("COUCH", "TV","TV_MOUNT","ENTERTAINMENT_SYSTEM")Gets you the TRUE or FALSE according to the row, then you subset AMOUNTAMOUNT[Description %in% c("COUCH", "TV","TV_MOUNT","ENTERTAINMENT_SYSTEM")]Then you wrap the values in a sum and round it:
This gives us the data.frame of:
Using
withallows us to refer to column names without using$The reason there wasn't an answer sooner enough is because the formatting given required extra work and humans are generally lazy.
If you had formatted your data.frame like this:
Or like this using the function
dput:It would have been answered swiftly.