I think this is what you are trying to do or at least close enough to work as a starting point
library(dplyr)
# Sample data on a copy/paste friendly format (replace with your actual dataset).
sample_data <- data.frame(
stringsAsFactors = FALSE,
No = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16),
ID = c("BUGA","BUGB","BUGC","BUGD",
"BUGE","BUGF","BUGA","BUGB","BUGA","BUGB","BUGC",
"BUGD","BUGE","BUGF","BUGA","BUGB"),
age = c(6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6),
sex = c("F","M","F","F","F","M",
"F","M","F","M","F","F","F","M","F","M"),
location = c("A","B","A","B","A","A",
"A","B","A","B","A","B","A","A","A","B"),
time = c("September_2017",
"September_2017","September_2017","September_2017","September_2017",
"September_2017","March_2018","March_2018",
"September_2017","September_2017","September_2017",
"September_2017","September_2017","September_2017","March_2018",
"March_2018"),
Bacteria = c("Bacteria.A","Bacteria.A",
"Bacteria.A","Bacteria.A","Bacteria.A","Bacteria.A",
"Bacteria.A","Bacteria.A","Bacteria.A","Bacteria.B",
"Bacteria.B","Bacteria.B","Bacteria.B","Bacteria.B",
"Bacteria.B","Bacteria.B"),
abundance = c(0.43,0.5,0.002,0.034,0.043,
0.023,0.34,0.23,0.43,0.5,8.9e-06,0.034,7.9e-05,
0.00098,0.0034,0.00012)
)
sample_data %>%
group_by(location, Bacteria, time) %>%
summarise(mean_abundance = mean(abundance)) %>%
arrange(desc(time), Bacteria, location)
#> `summarise()` regrouping output by 'location', 'Bacteria' (override with `.groups` argument)
#> # A tibble: 8 x 4
#> # Groups: location, Bacteria [4]
#> location Bacteria time mean_abundance
#> <chr> <chr> <chr> <dbl>
#> 1 A Bacteria.A September_2017 0.186
#> 2 B Bacteria.A September_2017 0.267
#> 3 A Bacteria.B September_2017 0.000356
#> 4 B Bacteria.B September_2017 0.267
#> 5 A Bacteria.A March_2018 0.34
#> 6 B Bacteria.A March_2018 0.23
#> 7 A Bacteria.B March_2018 0.0034
#> 8 B Bacteria.B March_2018 0.00012
Created on 2020-10-03 by the reprex package (v0.3.0)
For future reference, please make your questions providing a proper REPRoducible EXample (reprex) illustrating your issue (as the one above).
And if you want to learn more about data wrangling you can read this free ebook