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

summarize count with a condition

I have a data frame of counts in quadrats for a bunch of species in a bunch of years, but sometimes instead of counts, they are marked as "p" for "present." I want to average them while counting those p’s as NA in the averaging, but also keep track of the number of p’s there are in each species/year, so my question is, is there a way to use summarize(count) to count occurrences of P?

minimal example:

df <- data.frame(
  # years
  year = rep(1990:1992, each=3),
  # character vector of counts and p's
  count = c("p","p","2","1","5","4","7","p","4")
) %>%
  # numeric column of counts and NAs where P's should be
  mutate(count_numeric = as.numeric(count))


# summarize dataset
df %>%
  group_by(year) %>%
  summarize(number_quadrats = n(), # find total number of rows
            average_count = mean(count_numeric, na.rm=T)) # find average value

but I want to add another line to the summarize that will just count the number of P’s in each group. 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

df %>%
  group_by(year) %>%
  summarize(number_quadrats = n(), # find total number of rows
            average_count = mean(count_numeric, na.rm=T),# find average value
            number_p = n(count == "p"))

but that doesn’t work.

Any advice appreciated.

Thanks!

>Solution :

Just change the last line:

df %>%
group_by(year) %>%
summarize(number_quadrats = n(), # find total number of rows
          average_count = mean(count_numeric, na.rm=T),# find average value
          number_p = sum(count == "p"))

By summing a boolean vector, you are essentially counting the number of times the condition is met.

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