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

How can I write one line code instead of taking mean of each variable inside the group_by()?

My code is following:

mtmm_data4 <- mtmm_data  %>% group_by(cntry_lan, admdw) %>% 
  summarise( M1T1 = mean(M1T1, na.rm = TRUE), M1T2 = mean(M1T2, na.rm = TRUE), M1T3 = mean(M1T3, na.rm= TRUE), M2T1 = mean(M2T1, na.rm= TRUE), M2T2 = mean(M2T2, na.rm=TRUE), M2T3 = mean(M2T3, na.rm=TRUE), M3T1 = mean(M3T1, na.rm), M3T2 = mean(M3T2, na.rm=TRUE), M3T3 = mean(M3T3, na.rm = TRUE))

Also this code created a data set where all M2T1, M3T1, M3T2 are NANs. I did not understand why I would have had such NAs.

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

>Solution :

 mtmm_data  %>% 
   group_by(cntry_lan, admdw) %>% 
   summarise(across(c(YOUR_COLUMNS), ~mean(., na.rm = TRUE)))

Have a look at the tidyselect functions for some helpers that might make it simpler / more flexible to select the columns you want to summarize.

EDIT —

It sounds like your data might have been read in as character instead of numeric, which would error out when you take the mean. Examine your data types (e.g. str(mtmm_data) or glimpse(mtmm_data)) and if that’s the case, the best thing would be to fix it upstream when you load the data. You could also do it here with something like:

mtmm_data  %>% 
   group_by(cntry_lan, admdw) %>% 
   summarise(across(c(YOUR_COLUMNS), ~mean(as.numeric(.), na.rm = TRUE)))
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