# Groupby sum in R

Groupby sum in R can be accomplished by aggregate() or group_by() function. let’s  see how to

• Groupby sum of single column in R
• Groupby sum of multiple columns in R

First let’s create a dataframe

```
df1= data.frame(Name=c('James','Paul','Richards','Marico','Samantha','Ravi','Raghu','Richards','George','Ema','Samantha','Catherine'),
Sales=c(14,24,31,12,13,7,9,31,18,16,18,14))
df1
```

df1 will be #### Method 1 : using Aggregate ()

Aggregate function along with parameter by – by which it is to be grouped and function sum is mentioned as shown below

```# Groupby sum of single column

aggregate(df1\$Sales, by=list(df1\$State), FUN=sum)
```

so the grouped dataframe will be #### Method 2: groupby using dplyr

```
library(dplyr)
df1 %>% group_by(State) %>% summarise(sum_sales = sum(Sales))
```

so the grouped dataframe will be #### Method 1:

Aggregate function which is grouped by state and name, along with function sum is mentioned as shown below

```# Groupby sum of multiple columns
aggregate(df1\$Sales, by=list(df1\$State,df1\$Name), FUN=sum)
```

so the grouped dataframe will be #### Method 2: groupby using dplyr

```library(dplyr)
df1 %>% group_by(State,Name) %>% summarise(sum_sales = sum(Sales))
```

so the grouped dataframe will be 