Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate row means on subset of columns

Tags:

dataframe

r

Given a sample data frame:

C1<-c(3,2,4,4,5) C2<-c(3,7,3,4,5) C3<-c(5,4,3,6,3) DF<-data.frame(ID=c("A","B","C","D","E"),C1=C1,C2=C2,C3=C3)  DF     ID C1 C2 C3   1  A  3  3  5   2  B  2  7  4   3  C  4  3  3   4  D  4  4  6   5  E  5  5  3 

What is the best way to create a second data frame that would contain the ID column and the mean of each row? Something like this:

ID  Mean A    3.66 B    4.33 C    3.33 D    4.66 E    4.33 

Something similar to:

RM<-rowMeans(DF[,2:4]) 

I'd like to keep the means aligned with their ID's.

like image 323
Vinterwoo Avatar asked Jun 08 '12 08:06

Vinterwoo


People also ask

How do you calculate row mean?

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.

What is subset of rows?

3.1 Row Subsets A Row Subset is a selection of the rows within a whole table being viewed within the application, or equivalently a new table composed from some subset of its rows.

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

The rowMeans() function in R can be used to calculate the mean of several rows of a matrix or data frame in R.

How do you find the mean of multiple columns in R?

To find the mean of multiple columns based on multiple grouping columns in R data frame, we can use summarise_at function with mean function.


1 Answers

Calculate row means on a subset of columns:

Create a new data.frame which specifies the first column from DF as an column called ID and calculates the mean of all the other fields on that row, and puts that into column entitled 'Means':

data.frame(ID=DF[,1], Means=rowMeans(DF[,-1]))   ID    Means 1  A 3.666667 2  B 4.333333 3  C 3.333333 4  D 4.666667 5  E 4.333333 
like image 98
Jilber Urbina Avatar answered Oct 09 '22 03:10

Jilber Urbina