I am trying to compute the fraction (%) of a each record from the group total in a dataframe. My data look like:
Where I have factors for Station, Month and PH
You can do it without summarise and it will work as expected. I doubled your data example so I have 2 groups to work with to show how it works.
library(dplyr)
bn_phyla %>%
group_by(Station, Month) %>%
mutate(prop = SumOfTotal_Caught/sum(SumOfTotal_Caught))
# A tibble: 8 x 5
# Groups: Station, Month [2]
Station Month Phylum SumOfTotal_Caught prop
<chr> <chr> <chr> <dbl> <dbl>
1 A Feb-18 Annelida 20 0.182
2 A Feb-18 Arthropoda 20 0.182
3 A Feb-18 Mollusca 30 0.273
4 A Feb-18 Nemertea 40 0.364
5 B Mar-18 Annelida 40 0.333
6 B Mar-18 Arthropoda 30 0.25
7 B Mar-18 Mollusca 30 0.25
8 B Mar-18 Nemertea 20 0.167
data:
# data_frame comes from dplyr
bn_phyla <- data_frame(Station = c(rep("A", 4), rep("B", 4)),
Month = c(rep("Feb-18", 4), rep("Mar-18", 4)),
Phylum = c("Annelida", "Arthropoda", "Mollusca", "Nemertea", "Annelida", "Arthropoda", "Mollusca", "Nemertea"),
SumOfTotal_Caught = c(20,20,30,40, 40,30,30,20))