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

Apply mean and median in every row of a dataframe and add them as separated columns to the dataframe

I have the dataframe below:

structure(list(`2018-03` = c(NA, 943330388, NA, NA, NA, 543234645, 
45831420, NA, 27301292, 160818771), `2018-04` = c(NA, 1155823837, 
NA, NA, NA, 637460061, 38904148, NA, 39573248, 208830991), `2018-05` = c(NA, 
1360355713, NA, NA, NA, 715598918, 73012836, NA, 48043856, 189706047
)), class = "data.frame", row.names = c("Comedy", "Education", 
"Entertainment", "Film & Animation", "Gaming", "Howto & Style", 
"Music", "People & Blogs", "Science & Technology", "Sports"))

and I want to create a new dataframe with row names the same as now and the 2 new columns should be the mean for every row, and the median of every row.

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 :

We could use rowMeans with rowMedians (from matrixStats)

library(matrixStats)
library(tibble)
tibble(Mean = rowMeans(df1, na.rm = TRUE), 
      Median = rowMedians(as.matrix(df1), 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