How can I add a row with the mean of each column

Hello guys,

I've a pretty simple dataframe with 6 rows and 11 columns but i want to add a row with the mean of each column.

I started using R today, so i need all the help that you guys can provide to me.

Here is some code to compute the column averages and make those averages the last row of the data frame. As I comment in the code, you probably should not do the last step. If you explain why you want to do it, someone may have a better suggestion. I know that is a common thing to do in spreadsheets but the only time I would do that it R is if I need to display a table in a report and then I label the rows so that the shift in meaning is clear.

DF <- data.frame(A = rnorm(6), B = rnorm(6, 1, 1), C = rnorm(6, 2, 1), D = rnorm(6, 3, 1)) 
DF
#>             A          B        C        D
#> 1  0.46204271  1.7070590 1.522056 1.903730
#> 2 -2.29396565 -0.6318207 3.174212 3.446103
#> 3 -1.08765259  1.4883471 3.838221 2.688260
#> 4 -1.50761843  1.4415541 1.958823 2.839547
#> 5 -0.07726033  0.9140091 3.572603 2.326540
#> 6 -1.06822325 -0.7745883 1.471004 3.140461
library(dplyr)

Stats <- summarize_all(DF, mean)
Stats
#>            A         B        C        D
#> 1 -0.9287796 0.6907601 2.589487 2.724107

#You probably do not want to do the next step. The last row is not the 
#same kind of data as the other rows.
DFnew <- rbind(DF, Stats)
DFnew
#>             A          B        C        D
#> 1  0.46204271  1.7070590 1.522056 1.903730
#> 2 -2.29396565 -0.6318207 3.174212 3.446103
#> 3 -1.08765259  1.4883471 3.838221 2.688260
#> 4 -1.50761843  1.4415541 1.958823 2.839547
#> 5 -0.07726033  0.9140091 3.572603 2.326540
#> 6 -1.06822325 -0.7745883 1.471004 3.140461
#> 7 -0.92877959  0.6907601 2.589487 2.724107

Created on 2020-05-19 by the reprex package (v0.2.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.