How do I calculate the values of the rows in a data frame?
I have a framework with 1000 columns and 8 rows, I need to calculate the number of rows. 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 boolean: return NA
+3
source to share
1 answer
Use the function rowMeans()
:
final$mean <- rowMeans(final, na.rm=TRUE)
Please note that you should avoid using cycles for daily operations R
. If you want to iterate over all the lines yourself, you can use the function apply()
like this:
final$mean <- apply(final, 1, function(x) { mean(x, na.rm=TRUE) })
+8
source to share