How can I assign the computed mean from lapply as a new column in each dataframe of a list in R?

Advertisements

I have a list of dataframes.

For each dataframe within the list I would like to compute the weighted mean.

Henceforth, I want to add a new column into each dataframe within the list called Mean.

I want the new columns to repeat the computed mean value across all rows of each dataframe while retaining the dataframes into a list with all of their original columns and rows.

Thus far, I have figured out hot to compute the means.

Any help on how to achieve this is greatly appreciated.

 List <- data.frame(Set = c("A", "B", "C", "D", "A", "B", "C", "D", "A", "B", "C", "D"),
                    Value = 1:12, 
                   Count = 10:21)

 List <- split(List, f = List$Set, drop = TRUE)

 Mean <- lapply(List, function(x) {weighted.mean(x = x$Value, 
                                              w = (x$Count/sum(x$Count)), 
                                              na.rm = TRUE)})

>Solution :

You may change your lapply code to add the new column in each dataframe directly.

out <- lapply(List, function(x) {
  x$Mean <- weighted.mean(x = x$Value, w = (x$Count/sum(x$Count)), na.rm = TRUE)
  x
})

out

#$A
#  Set Value Count     Mean
#1   A     1    10 5.761905
#5   A     5    14 5.761905
#9   A     9    18 5.761905

#$B
#   Set Value Count     Mean
#2    B     2    11 6.711111
#6    B     6    15 6.711111
#10   B    10    19 6.711111

#$C
#   Set Value Count     Mean
#3    C     3    12 7.666667
#7    C     7    16 7.666667
#11   C    11    20 7.666667

#$D
#   Set Value Count     Mean
#4    D     4    13 8.627451
#8    D     8    17 8.627451
#12   D    12    21 8.627451

Leave a ReplyCancel reply