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

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

Let’s generate one data table.

Environment <- c("ENV1","ENV2","ENV3","ENV4","ENV5")
CV1<- c(25.2,26.3,15.2,22.1,21.9)
CV2<- c(37.1,34.5,26.0,29.9,28.3)
CV3<- c(33.0,30.5,25.0,30.2,28.9)
CV4<- c(35.4,37.0,28.0,26.0,34.0)
CV5<- c(34.6,32.7,20.0,32.3,28.6)

dataA<-data.frame(Environment,CV1,CV2,CV3,CV4,CV5)
dataA

Now, I’d like to calculate mean of each column and row. For example, I want to calculate mean of ENV1 to ENV5, and also CV1 to CV5.

First, I’ll calculate mean of each row (ENV1 to ENV 5).

library(dplyr)
dataA$Avg <- round(rowMeans (dataA %>% select(-Environment)),digits=2)
dataA

I discarded Environment row (dataA %>% select(-Environment)) because it’s not a numeric.

Now, I’ll calculate mean of each column (CV1 to CV5).

dataB <- rbind(dataA, c("Avg", round(colMeans(dataA %>% select(-Environment)),digits=2)))

Now, mean of each column and row was calculated.

Leave a Reply

If you include a website address in the comment section, I cannot see your comment as it will be automatically deleted and will not be posted. Please refrain from including website addresses.