Title: how to calculate row means in a data frame?
Tags: r;dataframe;stat
Question: 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
Comment: 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()`.

Here is the accepted answer: 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) })


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:05/27/15', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<r><dataframe><stat>', 'Title': 'how to calculate row means in a data frame?', 'ViewCount': 18790, 'id': 30471302, 'user_AboutMe': None, 'user_AccountId': 6368224.0, 'user_DisplayName': 'vahab', 'user_Reputation': 277.0, 'user_Views': 10.0, 'user_id': 4941566.0}}