I want to combine rows based on id and treatment variables.

Each column should follow different formulas.

For example: let us set sample as n, mean as m and standard deviation as sd

```
$$
Sample = N_{1}+N_{2}
$$
$$
Mean = \frac{N_{1} M_{1}+N_{2} M_{2}}{N_{1}+N_{2}}
$$
$$
SD = \sqrt{\frac{\left(N_{1}-1\right) \mathrm{SD}_{1}^{2}+\left(N_{2}-1\right) \mathrm{SD}_{2}^{2}+\frac{N_{1} N_{2}}{N_{1}+N_{2}}\left(M_{1}^{2}+M_{2}^{2}-2 M_{1} M_{2}\right)}{N_{1}+N_{2}-1}}
$$
```

I tried to use the dplyr group_by and summarise functions but ended without luck.

Is there any better way to do this at once?

Here is reproducible data:

```
df <- read.table(textConnection('
id treatment mean std sample
1 A 10 2 20
1 B 11 3 21
1 A 12 4 22
2 A 8 5 30
2 B 9 6 31
2 A 9 4 32
3 A 9 3 40
3 B 7 4 41
3 A 6 2 42
4 A 10 3 50
4 B 8 2 51
4 A 6 4 52
'), header=TRUE)
```