Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate the mean for each column of a matrix in R

Tags:

dataframe

r

mean

I am working on R in R studio. I need to calculate the mean for each column of a data frame.

 cluster1  // 5 by 4 data frame  mean(cluster1) //  

I got :

  Warning message:   In mean.default(cluster1) :   argument is not numeric or logical: returning NA 

But I can use

  mean(cluster1[[1]]) 

to get the mean of the first column.

How to get means for all columns ?

Any help would be appreciated.

like image 959
user2420472 Avatar asked Feb 16 '14 06:02

user2420472


People also ask

How do you find the mean of each row in a matrix in R?

Calculate the mean of rows of a data frame in R To create a data frame in R, use the data. frame() function. To calculate the mean of rows of the data frame, use the rowMeans() function.

How do you get the mean of a column in a dataset in R?

To calculate the average of a data frame column in R, use the mean() function. The mean() function takes the column name as an argument and calculates the mean value of that column.

How do I average all columns in R?

Often you may want to calculate the mean of multiple columns in R. Fortunately you can easily do this by using the colMeans() function.

How do I calculate the mean of multiple columns in R?

Often you may want to calculate the mean of multiple columns in R. Fortunately you can easily do this by using the colMeans () function. The following examples show how to use this function in practice. The following code shows how to use the colMeans () function to find the mean of every column in a data frame:

How to compute the mean of each column of a matrix?

colMeans () function in R Language is used to compute the mean of each column of a matrix or array. dims: integer value, which dimensions are regarded as ‘columns’ to sum over.

What are matrices in R?

Matrices are two-dimensional, homogeneous data-structures in R. They have rows and columns and they can store data of only a single type. In this tutorial, we learned about matrices and matrix functions in R.

What is the use of mean () function in R?

The mean () function returns the mean of all the elements of the matrix. For example: Matrices are two-dimensional, homogeneous data-structures in R. They have rows and columns and they can store data of only a single type. In this tutorial, we learned about matrices and matrix functions in R.


1 Answers

You can use colMeans:

### Sample data set.seed(1) m <- data.frame(matrix(sample(100, 20, replace = TRUE), ncol = 4))  ### Your error mean(m) # [1] NA # Warning message: # In mean.default(m) : argument is not numeric or logical: returning NA  ### The result using `colMeans` colMeans(m) #   X1   X2   X3   X4  # 47.0 64.4 44.8 67.8  
like image 61
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 19 '22 15:09

A5C1D2H2I1M1N2O1R2T1