[R] data frame row statistics (mean)?

Erik Iverson eriki at ccbr.umn.edu
Mon Jun 28 20:50:34 CEST 2010



Douglas M. Hultstrand wrote:
> Hello,
> 
> I am trying to calculate the mean value of each row in a data frame (d), 
> I am having troubles and getting errors using the code I have written.  
> Below is a brief example of the code, any thought or suggestions would 
> be great.
> 
> Thank you for your time,
> Doug
> 
> 
> # Example Code:
> d <- data.frame(st1=c(1,2,3,4), st2=c(2,5,6,7), st3=c(5,5,NA,7), 
> st4=c(6,5,7,8))
> avg <- rep(NA,length(d[,1]))
> 
> for (i in 1:length(d[,1])) {
>        avg[i] = mean(d[i,1:4], na.rm=TRUE)
> }
> 
> # Final Output wanted.
>  st1 st2 st3 st4  avg
> 1   1   2   5   6 3.50
> 2   2   5   5   5 4.25
> 3   3   6  NA   7 5.33
> 4   4   7   7   8 6.50
> 

d$avg <- rowMeans(d, na.rm = TRUE)



More information about the R-help mailing list