Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Aggregate and summarise character object with R

I have a breeding productivity dataset:

df1
    # Nest.box Obs.type individual.number Clutch Chick.status
    # 1 Nest1 Egg 1 First NA
    # 2 Nest1 Egg 2 First NA
    # 3 Nest1 Egg 3 First NA
    # 4 Nest2 Egg 1 First NA
    # 5 Nest2 Egg 2 First NA
    # 6 Nest2 Egg 1 First NA
    # 7 Nest1 Chick 1 First Dead
    # 8 Nest1 Chick 2 First Fledged
    # 9 Nest2 Chick 1 First Fledged
    # 10 Nest2 Chick 2 First Fledged
    # 11 Nest2 Chick 1 Second Fledged
    # 12 Nest2 Chick 2 Second UNK

I want to summarise these data by aggregating by Nest.box and Clutch (shows the number of "Fledged" by nest.box, by clutch)

The wanted output would be something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

output
        # Nest.box Clutch Fledged
        # 1 Nest1 First 1
        # 2 Nest2 First 2
        # 3 Nest2 Second 1

>Solution :

Here is a potential solution:

library(dplyr)

df <- read.table(text = "Nest.box Obs.type individual.number Clutch Chick.status
1 Nest1 Egg 1 First NA
2 Nest1 Egg 2 First NA
3 Nest1 Egg 3 First NA
4 Nest2 Egg 1 First NA
5 Nest2 Egg 2 First NA
6 Nest2 Egg 1 First NA
7 Nest1 Chick 1 First Dead
8 Nest1 Chick 2 First Fledged
9 Nest2 Chick 1 First Fledged
10 Nest2 Chick 2 First Fledged
11 Nest2 Chick 1 Second Fledged
12 Nest2 Chick 2 Second UNK", header = TRUE)

df %>%
  group_by(Nest.box, Clutch) %>%
  summarise(Fledged = sum(Chick.status == "Fledged", na.rm = TRUE))

#> # A tibble: 3 × 3
#> # Groups:   Nest.box [2]
#>   Nest.box Clutch Fledged
#>   <chr>    <chr>    <int>
#> 1 Nest1    First        1
#> 2 Nest2    First        2
#> 3 Nest2    Second       1

Created on 2022-04-04 by the reprex package (v2.0.1)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading