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

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

routes - Laravel 4 Wildcard Routing to Different Controllers -

cross browser - XSLT namespace-alias Not Working in Firefox or Chrome -