通过使用 R 中的列表的组计算平均值

Compute mean by groups working with lists in R

我想:

  1. 通过在每个列表中使用以下变量 (idmonth) 进行分组。然后,我想平均感兴趣变量的值 (preds)
id <- c(1,2,3,4,5,1,2,3,4,5)
month <- c(3,4,2,1,5,7,3,1,8,9)
preds <- c(0.5,0.1,0.15,0.23,0.75,0.6,0.49,0.81,0.37,0.14)

l_1 <- data.frame(id, preds, month)

preds <- c(0.45,0.18,0.35,0.63,0.25,0.63,0.29,0.11,0.17,0.24)

l_2 <- data.frame(id, preds, month)

preds <- c(0.58,0.13,0.55,0.13,0.76,0.3,0.29,0.81,0.27,0.04)

l_3 <- data.frame(id, preds, month)

preds <- c(0.3,0.61,0.18,0.29,0.85,0.76,0.56,0.91,0.48,0.91)

l_4 <- data.frame(id, preds, month)

outcome <- list(l_1, l_2, l_3, l_4)

我试过使用地图函数并应用但没有成功。 有帮助吗?

提前致谢

使用 lapply()aggregate():

res1 <- lapply(
  outcome, 
  function(x){
    aggregate(
      preds ~ id + month,
      data = x,
      FUN = mean
    )[,names(x)]
  }
)

使用tidyverse-

library(dplyr)
library(purrr)

map(outcome, ~.x %>% 
               group_by(id, month) %>% 
               summarise(preds = mean(preds), .groups = 'drop'))