Joey Yi Zhao
Joey Yi Zhao

Reputation: 42644

How to get mean value of each columns in a data frame

I want to get the mean value of each column in a data frame like below:

> x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
> x
     x1 x2
[1,]  3  4
[2,]  3  3
[3,]  3  2
[4,]  3  1
[5,]  3  2
[6,]  3  3
[7,]  3  4
[8,]  3  5
> y <- colMeans(x)
> y
x1 x2 
 3  3 

I can get the mean value from y but y is not a data frame. How can I get a return value of data frame? I need to use cbind on y to bind with other data frames.

Upvotes: 1

Views: 8332

Answers (2)

Seyma Kalay
Seyma Kalay

Reputation: 2863

I was looking for the same then I found a solution like below

you have a numeric dataset

df <-  data.frame(a = c(623.3,515.2,611.0,729.0,843.25),
                 b = c(1,2,3,4,5),
                 c = c("name1","name2", "name3", "name4", "name5"))

you can either apply this for some specific columns

mysummary <- function(x){
  funs <- c(mean,sd,mad,IQR)
  lapply(funs,function(f) f(x,na.rm = T))
}

mysummary(df$a)
mysummary(df$b)

or for all the dataset

  mysummary2 <- function(x){
  if (is.numeric(x)){
    c(mean(x),median(x),sd(x), mad(x), IQR(x))
  }else{ print("pass")}
}

lapply(df,mysummary2)

Upvotes: 1

storm surge
storm surge

Reputation: 841

In your example x is a matrix. You have two option:

Option 1 - transform x into a data frame and then use sapply

x<-as.data.frame(cbind(x1 = 3, x2 = c(4:1, 2:5)))
x.df<-sapply(x,FUN=mean)

> x.df
x1 x2 
3  3 

Option 2 - use apply and transform the result in a data frame

x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
x.df<-as.data.frame(t(apply((x),MARGIN=2,FUN=mean)))

> x.df
x1 x2 
3  3

Upvotes: 1

Related Questions