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

Average in R; Dplyr

I want to have a mean for each year for both the countries. But I am unable to formulate a code. Please help

I was trying the following code but it does not work.

Mean <- dt %>%
group_by(year) %>%
summarise(Average=mean, na.rm = TRUE))

Following is the input

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

structure(list(year = c(2010, 2010, 2010, 2010, 2012, 2012), 
India = c(56, 53, 52, 0, 29, 30), Nepal = c(35, 6, 7, 12, 
34, 55)), row.names = c(NA, 6L), class = "data.frame")

>Solution :

You may try

dt %>%
  group_by(year) %>%
  summarise(average_india = mean(India, na.rm = TRUE),
            average_nepal = mean(Nepal, na.rm = TRUE))

   year average_india average_nepal
  <dbl>         <dbl>         <dbl>
1  2010          40.2          15  
2  2012          29.5          44.5

or

dt %>%
  group_by(year) %>%
  summarise(across(everything(), ~mean(.x)))

   year India Nepal
  <dbl> <dbl> <dbl>
1  2010  40.2  15  
2  2012  29.5  44.5
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