how to calculate row means in a data frame?
Asked Answered
P

1

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

Pratt answered 27/5, 2015 at 0:41 Comment(1)
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().Tillotson
U
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) })
Untidy answered 27/5, 2015 at 0:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.