How to find the column mean of first n number of rows in R data frame?


To find the column mean of first n number of rows in R data frame, we can follow the below steps −

  • First of all, create a data frame.
  • Then, use colMeans function by reading the data frame with matrix function and nrow argument.

Example1

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x<-rnorm(20)
df1<-data.frame(x)
df1

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

      x
1 0.13032553
2 -0.67816114
3 1.42759471
4 -0.38436418
5 -0.61993704
6 1.44777262
7 0.04268727
8 0.48114764
9 -0.27875354
10 0.71026224
11 0.08441343
12 -0.03178720
13 0.69694108
14 -0.57978544
15 2.63039761
16 0.75607995
17 -0.12466369
18 1.03613577
19 -0.26832398
20 1.46741698

Find the column mean for n number of rows

Using colMeans function to find the column mean after reading the data frame df1 with matrix function for 10 rows −

 Live Demo

x<-rnorm(20)
df1<-data.frame(x)
colMeans(matrix(df1$x,nrow=10))

Output

[1] 0.2278574 0.5666825

Example2

Create the data frame

Let's create a data frame as shown below −

 Live Demo

y<-sample(1:10,20,replace=TRUE)
df2<-data.frame(y)
df2

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

  y
1 8
2 9
3 9
4 7
5 3
6 10
7 10
8 7
9 7
10 6
11 9
12 7
13 3
14 5
15 10
16 6
17 9
18 1
19 3
20 6

Find the column mean for n number of rows

Using colMeans function to find the column mean after reading the data frame df2 with matrix function for 18 rows −

 Live Demo

colMeans(matrix(df2$y,nrow=18))

Output

[1] 7.000000 6.944444
Warning message:
In matrix(df2$y, nrow = 18) :
   data length [20] is not a sub-multiple or multiple of the number of rows [18]

Updated on: 13-Aug-2021

623 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements