r - Merge and aggregate result to original data -


i have dataframe df, 3 variables : id, category , quantity :

id category quantity 01 ab       235 02 bc       987 03 ab       366 04 cd       287 

i want add fourth variable sum of whole category. now, :

df <- merge(df,aggregate(df$quantity,list(df$category),sum),      by.x="category",       by.y="group.1") names(df)[4] <- "sum.category" 

it works, don't find satisfying, there's better way?

here option data.table. convert 'data.frame' 'data.table' (setdt(df1)), grouped 'category', assign (:=) sum of 'quantity' new column ('sum.category').

library(data.table) setdt(df1)[,sum.category:= sum(quantity) , category] df1 #    id category quantity sum.category #1:  1       ab      235          601 #2:  2       bc      987          987 #3:  3       ab      366          601 #4:  4       cd      287          287 

or using base r

df1$sum.category <- with(df1, ave(quantity, category, fun=sum)) 

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -