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

In R, how to calculate mean per column and row respectively?

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?

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

Always many thanks,

>Solution :

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
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