Goal
My primary aim is to add a mean row at by somehow rbind the mean from the mean list to the dataframe list I have create to create larger dataframes within the data frame list. I wrote a lot for this question so I hope you could help me in my case. If anything is unclear, please comment!
Code
Suppose you have three different data frames that you want to create below:
df1 <- data.frame(aa = sample(1:10, 5, replace = TRUE),
bb = sample(1:10, 5, replace = TRUE),
cc = sample(1:10, 5, replace = TRUE),
row.names = c("a", "b", "c", "d", "e"))
df2 <- data.frame(aa = sample(1:10, 5, replace = TRUE),
bb = sample(1:10, 5, replace = TRUE),
cc = sample(1:10, 5, replace = TRUE),
row.names = c("a", "b", "c", "d", "e"))
df3 <- data.frame(aa = sample(1:10, 5, replace = TRUE),
bb = sample(1:10, 5, replace = TRUE),
cc = sample(1:10, 5, replace = TRUE),
row.names = c("a", "b", "c", "d", "e"))
Doing this will yield these outputs in the console for this example:
> df1 #the arrow on the left specifies the console entry
aa bb cc
a 6 9 5
b 2 6 4
c 6 2 3
d 10 4 8
e 3 1 3
> df2
aa bb cc
a 7 9 10
b 2 7 5
c 1 5 7
d 8 5 5
e 9 3 5
> df3
aa bb cc
a 2 6 8
b 3 7 7
c 1 4 2
d 4 9 9
e 8 7 3
Now I want to put these in a list so save the amount of work I have to do (hopefully!):
df_list <- list(df1=df1, df2=df2, df3=df3)
#Kept the names for future reference (so that I could write df_list$df1 instead of df_list[[1]]
Giving me a respectable list identical to the df1-3 outputs, just all together:
> df_list
$df1
aa bb cc
a 6 9 5
b 2 6 4
c 6 2 3
d 10 4 8
e 3 1 3
$df2
aa bb cc
a 7 9 10
...
Now I wanted to create perform basically a colMean
across my data but I didn't find a more efficient way to do this other than to use lapply
with mean
:
mean_lst <- lapply(df_list, function(x) {lapply(x[,1:ncol(x)], mean)}) #finding means of columns
The code above is nested in a weird way but it gave the result that I was looking for (if there is a better way to achieve nearly identical, feel free to comment about that). It gave me an interesting result that looks usable...? I'm new to R so I am not sure how to use this properly. Take a look at the mean_lst output:
> mean_lst
$df1
$df1$aa
[1] 5.4
$df1$bb
[1] 4.4
...
$df3$cc
[1] 5.8
The Struggle(is.Real) and Question
I have tried rbind to no avail and I don't quite understand how I can use this output (or any other output) so that I can calculate each dataframe means without having to do them one by one, without having to extract dataframes from the list and write identical code. My dream output would look something like this, applying the mean_lst output to each dataframe within the df_list using rbind:
> df_list$df1
aa bb cc
a 6 9 5
b 2 6 4
c 6 2 3
d 10 4 8
e 3 1 3
mean 5.4 4.4 4.6
Would anyone know how to write such code, if it exists? Or is there a more efficient to write colMeans for each of these columns in dataframes within lists, without having to explicitly write out the dataframe names? Thank you so much in advance!