How to save column means into a data frame in R?


To save column means into a data frame in R, we can follow the below steps −

  • First of all, create a data frame.
  • Then, find column means using colMeans function and save it in an object.
  • After that, use as.data.frame function to save the columns means into a data frame.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x1<-rnorm(20)
x2<-rnorm(20)
x3<-rnorm(20)
df<-data.frame(x1,x2,x3)
df

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

      x1          x2          x3
1 1.70213769 -0.95244473 2.26375065
2 0.34595513 -1.08072982 1.82237900
3 -2.15140370 0.29371231 0.93618736
4 1.15205917 1.49441646 0.10359977
5 -0.64792396 0.74386152 -0.32052344
6 -0.26708932 1.35840278 0.72028830
7 0.18588536 -0.17686768 -1.49281471
8 -0.68221640 1.01872585 -0.80628351
9 -0.54297612 -0.75439795 0.45718718
10 0.16809064 1.29755557 1.04083405
11 -0.62313149 0.21069186 -0.20507877
12 0.23506147 1.21497276 1.20580838
13 -1.26262129 -0.36575192 0.69571211
14 0.20252970 -0.01855807 2.34383973
15 -0.08076369 1.01931122 -0.83870727
16 -0.34867185 -0.24427371 0.90440007
17 0.72632978 1.20472358 -0.02400482
18 -0.16881666 0.69104113 0.27885659
19 0.11902785 -0.26653054 0.90215258
20 -0.83209119 1.11191470 0.70603749

Find the column means

Using colMeans function to find the column means and saving it in an object −

 Live Demo

x1<-rnorm(20)
x2<-rnorm(20)
x3<-rnorm(20)
df<-data.frame(x1,x2,x3)
ColMeans_df<-colMeans(df)
ColMeans_df

Output

      x1       x2       x3
-0.1385314 0.3899888 0.5346810

Save column means in a data frame

Using as.data.frame function to save the column means in a data frame −

 Live Demo

x1<-rnorm(20)
x2<-rnorm(20)
x3<-rnorm(20)
df<-data.frame(x1,x2,x3)
ColMeans_df<-colMeans(df)
as.data.frame.list(ColMeans_df)

Output

      x1          x2       x3
1 -0.1385314 0.3899888 0.534681

Updated on: 13-Aug-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements