I have the following dataset imported from excel via "readxl::read_excel" command:

```
Municipality Production Type
Atima 690 Reverification
Atima 120 Reverification
Atima 220 Reverification
Comayagua 153 Initial
Comayagua 193 Initial
Comayagua 138 Initial
Comayagua 307 Reverification
Copán 179 Initial
Copán 100 Initial
Copán 236 Reverification
Copán 141 Reverification
Danlí 56 Reverification
...
```

Subsequently used the code below as the data was tbl_df.

```
df <- as.data.frame(df)
```

I want to sort the data by Type and add up the Production to get the total Production for each Municipality:

```
Municipality Production Type
Atima 1030 Reverification
Comayagua 484 Initial
Comayagua 307 Reverification
Copán 279 Initial
Copán 377 Reverification
Danlí 56 Reverification
```

I looked up in other post, but I was only able to find how to sum it up for one categorical variable. How could I do this in R? Or should I first do it in excel and then import the table?

I'm working in Rstudio Version 0.99.441, in Windows 7.

Thanks in advance for your help.

# Best How To :

Use one of the aggregating functions

```
library(data.table)
setDT(df1)[,list(Production=sum(Production)) , .(Municipality,Type)]
# Municipality Type Production
# 1: Atima Reverification 1030
# 2: Comayagua Initial 484
# 3: Comayagua Reverification 307
# 4: Copán Initial 279
# 5: Copán Reverification 377
# 6: Danlí Reverification 56
```

or

```
res <- aggregate(Production~., df1, FUN=sum)
res1 <- res[with(res, order(Municipality,-Production)),]
row.names(res1) <- NULL
res1
# Municipality Type Production
#1 Atima Reverification 1030
#2 Comayagua Initial 484
#3 Comayagua Reverification 307
#4 Copán Reverification 377
#5 Copán Initial 279
#6 Danlí Reverification 56
```

### data

```
df1 <- structure(list(Municipality = c("Atima", "Atima", "Atima", "Comayagua",
"Comayagua", "Comayagua", "Comayagua", "Copán", "Copán", "Copán",
"Copán", "Danlí"), Production = c(690L, 120L, 220L, 153L, 193L,
138L, 307L, 179L, 100L, 236L, 141L, 56L), Type = c("Reverification",
"Reverification", "Reverification", "Initial", "Initial", "Initial",
"Reverification", "Initial", "Initial", "Reverification", "Reverification",
"Reverification")), .Names = c("Municipality", "Production",
"Type"), class = "data.frame", row.names = c(NA, -12L))
```