# Average of each column in df, stored as a new df

Hi guys I have one for you:

I want to average the values of all the columns in a df and store the values in the the new data frame, its important that the column name are unchanged. I can do it for each row individually but I dont know how to do it for all and have it stored.

Example:

``````df <- data.frame(
A = c(2,1,2,0,0,1),
B = c(4,5,3,0,1,3),
C = c(1,0,2,0,7,4),
D = c(3,2,1,0,0,0)
)
row.names(df) <- c('one','two','three', 'four', 'five', 'six')
df

A B C D
one   2 4 1 3
two   1 5 0 2
three 2 3 2 1
four  0 0 0 0
five  0 1 7 0
six   1 3 4 0

``````

After averaging all the columns, I want the new object to be like this:

``````  A    B    C D
1 1 2.66 2.33 1
``````

The rownames will not be significant.

I also have all of the column names in a list already

The solution is very simple

``````library(dplyr)

df <- data.frame(
A = c(2,1,2,0,0,1),
B = c(4,5,3,0,1,3),
C = c(1,0,2,0,7,4),
D = c(3,2,1,0,0,0)
)
row.names(df) <- c('one','two','three', 'four', 'five', 'six')

new_df <- df %>%
summarise_all(mean)

new_df
#>   A        B        C D
#> 1 1 2.666667 2.333333 1
``````

Created on 2019-11-24 by the reprex package (v0.3.0.9000)

1 Like

Yes!!!!!!! Simple and elegant thank you again andres!

Accually Andres Im getting an error when I run it on my data:

``````Error in UseMethod("tbl_vars") :
no applicable method for 'tbl_vars' applied to an object of class "c('matrix', 'double', 'numeric')"
``````

Any ideas? how would I run the code if the df was transposed? (look at row means instead of column means)

Weird not sure why it wouldn't run. I got it to work with this:

``````
new_df <- colMeans(df[ ,col.list], na.rm=TRUE)
``````

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