# How to create a new data frame for the mean of rows of some columns from an R data frame?

R ProgrammingServer Side ProgrammingProgramming

Finding row means help us to identity the average performance of a case if all the variables are of same nature and it is also an easy job. But if some of the columns have different type of data then we have to extract columns for which we want to find the row means. Therefore, we can create a new data frame with row means of the required columns using rowMeans function.

## Example

Live Demo

Consider the below data frame −

set.seed(88)
Group<-LETTERS[1:10]
x1<-rpois(20,2)
x2<-rpois(20,5)
x3<-rpois(20,10)
df<-data.frame(Group,x1,x2,x3)
df

## Output

 Group x1 x2 x3
1 A 2 3 10
2 B 0 6 7
3 C 3 7 9
4 D 2 8 9
5 E 6 8 9
6 F 8 6 4
7 G 0 4 5
8 H 3 7 10
9 I 3 5 11
10 J 5 4 10
11 A 2 3 9
12 B 3 7 8
13 C 2 6 6
14 D 1 4 7
15 E 0 7 12
16 F 1 8 9
17 G 0 5 11
18 H 2 6 9
19 I 3 7 5
20 J 3 9 6

Creating a new data frame with column Group as in original df and RowMeans for the mean of columns x1, x2, and x3 −

row_means_df<-data.frame(Group=df[,1],RowMeans=rowMeans(df[,-1]))
row_means_df
Group RowMeans
1 A 5.000000
2 B 4.333333
3 C 6.333333
4 D 6.333333
5 E 7.666667
6 F 6.000000
7 G 3.000000
8 H 6.666667
9 I 6.333333
10 J 6.333333
11 A 4.666667
12 B 6.000000
13 C 4.666667
14 D 4.000000
15 E 6.333333
16 F 6.000000
17 G 5.333333
18 H 5.666667
19 I 5.000000
20 J 6.000000

Creating a new data frame with column Group as in original df and RowMeans for the mean of columns x2 and x3 that is 3 and 4 −

row_means_3.4_cols_df<-data.frame(Group=df[,1],RowMeans=rowMeans(df[,-c(1,2)]))
row_means_3.4_cols_df
Group RowMeans
1 A 6.5
2 B 6.5
3 C 8.0
4 D 8.5
5 E 8.5
6 F 5.0
7 G 4.5
8 H 8.5
9 I 8.0
10 J 7.0
11 A 6.0
12 B 7.5
13 C 6.0
14 D 5.5
15 E 9.5
16 F 8.5
17 G 8.0
18 H 7.5
19 I 6.0
20 J 7.5
Published on 21-Aug-2020 06:21:32