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

Time:03-18

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.

CodePudding user response:

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))
  •  Tags:  
  • r
  • Related