Home > Software engineering >  In R, how to calculate mean per column and row respectively?
In R, how to calculate mean per column and row respectively?

Time:01-27

I have a data like below.

Env<- c("Env1","Env2")
Genotype1<- c(7,3)
Genotype2<- c(9,5)
dataB<- data.frame(Env, Genotype1,Genotype2)

  Env    Genotype1 Genotype2
1 Env1         7         9
2 Env2         3         5

Now I'd like to calculate mean per row and column respetively like below table

  Env    Genotype1 Genotype2  mean
1 Env1         7         9     8
2 Env2         3         5     4 
  mean         5         7

Could you let me know how to do it?

Always many thanks,

CodePudding user response:

We may use colMeans/rowMeans and append it to data with rbind/cbind in base R

out <- cbind(rbind(dataB, c(Env = 'mean', 
  as.list(colMeans(dataB[-1])))), mean = c(rowMeans(dataB[-1]), NA))
out[out$Env == "mean", "mean"] <- mean(unlist(out[out$Env == "mean", 2:3]))

-output

 > out
   Env Genotype1 Genotype2 mean
1 Env1         7         9    8
2 Env2         3         5    4
3 mean         5         7    6

Another option is

 addmargins(`row.names<-`(as.matrix(dataB[-1]), dataB[[1]]), FUN = mean)
     Genotype1 Genotype2 mean
Env1         7         9    8
Env2         3         5    4
mean         5         7    6
  • Related