We can use xtabs from base R By default, xtabs gets sum
xtabs(Profit~Category+Mode, df)
Or another base R option, more flexible for applying different FUN , is tapply .
with(df, tapply(Profit, list(Category, Mode), FUN=sum))
Or we can use dcast to convert from 'long' to 'wide' format. It is more flexible as we can specify fun.aggregate - sum , mean , median , etc.
library(reshape2) dcast(df, Category~Mode, value.var='Profit', sum) # Category KLM #1 X 36 11 11 #2 Y 17 26 28 #3 Z 0 8 15
If you need this in a "long" format, here is one option with data.table . We convert "data.frame" to "data.table" ( setDT(df) ), grouped by "Category" and "Mode", we get the sum "Profit".
library(data.table) setDT(df)[, list(Profit= sum(Profit)) , by = .(Category, Mode)]
akrun
source share