6

I have a dataframe with 1000 columns and 8 rows, I need to calculate row means.I tried this loop:

final <- as.data.frame(matrix(nrow=8,ncol=1))
for(j in 1:8){
  value<- mean(dataframe[j,])
  final[j,]<-value
}

but got the following error:

In mean.default(df2[j, ]) : argument is not numeric or logical: returning NA

Frank
  • 66,179
  • 8
  • 96
  • 180
vahab
  • 297
  • 2
  • 3
  • 9
  • You haven't mentioned what is your data, but the 1000x8 format suggest it's transposed in terms of how tables are usually created, with observations in rows and variables in columns. That's how most functions treat data and how many operators and objects, including data frames, work. And if you decide to transpose your data, you can use `t()` and then `colMeans()`. – Molx May 27 '15 at 01:11

1 Answers1

9

Use the rowMeans() function:

final$mean <- rowMeans(final, na.rm=TRUE)

Note that you should avoid using loops for your everyday R operations. If you want to iterate over all rows yourself, you can use the apply() function like this:

final$mean <- apply(final, 1, function(x) { mean(x, na.rm=TRUE) })
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360