In R, how to substrtact the mean from each value?

In R, how to substrtact the mean from each value?


In my previous post, I explained how to add extra column and row to calculate mean respectively.


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


library(dplyr)
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$Avg <- round(rowMeans (dataA %>% select(-Environment)),digits=2)
dataB<- rbind(dataA, c("Avg", round(colMeans(dataA %>% select(-Environment)),digits=2)))

Now, I’d like to substrtact the mean from each value in each column. This will be genotypic effect.

df = list()
for (i in 1:nrow(dataB)) {
     a <- as.numeric(dataB$CV1[i])
     b <- as.numeric(dataB$CV2[i])
     c <- as.numeric(dataB$CV3[i])
     d <- as.numeric(dataB$CV4[i])
     e <- as.numeric(dataB$CV5[i])
df[[i]] <- c(Env=paste0("Genotypic effect",i), 
     CV1=round(a-as.numeric(dataB$CV1[._SelectAvr= 6]),digits=2),
     CV2=round(b-as.numeric(dataB$CV2[._SelectAvr= 6]),digits=2),
     CV3=round(c-as.numeric(dataB$CV3[._SelectAvr= 6]),digits=2),
     CV4=round(d-as.numeric(dataB$CV4[._SelectAvr= 6]),digits=2),
     CV5=round(e-as.numeric(dataB$CV5[._SelectAvr= 6]),digits=2))
}
df <- as.data.frame(do.call("rbind", v))
n<-dim(df)[1]
df<-df[1:(n-1),]
df

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.