有没有一种方法可以获取包含多个列表的列表中值的算术平均值?

时间:2019-12-07 20:07:32

标签: r

为解释我的问题并加深了解,我将向您展示一个示例。

假设我有一个这样的数据框:

value <- c(1:1000)
group <- c(1:5)
df <- data.frame(value,group)

我创建了自己的函数myfun(),以从数据帧df中获取随机行,并将其存储在不同的数据帧wz1-wz5中。之后,我的函数会将数据帧wz1-wz5绑定到一个名为wza的数据帧中,并按组汇总值。

myfun <- function(){
  wz1 <- df[sample(nrow(df), size = 300, replace = FALSE),]
  wz2 <- df[sample(nrow(df), size = 10, replace = FALSE),]
  wz3 <- df[sample(nrow(df), size = 100, replace = FALSE),]
  wz4 <- df[sample(nrow(df), size = 40, replace = FALSE),]
  wz5 <- df[sample(nrow(df), size = 50, replace = FALSE),]

  wza <- rbind(wz1,wz2, wz3, wz4, wz5)
  wza_sum <- aggregate(wza, by = list(group=wza$group), FUN = sum)
  return(wza_sum)
}

现在,我要使用copy()将函数myfun()重复100次。

dfx <- replicate(100,myfun(),simplify = FALSE)

输出是一个包含100个列表的列表,每个列表是一个具有5行的数据框。

这里是rstudio输出结果的图片。 enter image description here

现在,我想计算所有列表(1-100)的所有组(1-5)的值的算术平均值。 为了更好地解释这一部分,我将再举一个例子。

list[[1]] -> group 1 -> value =   53263 
list[[2]] -> group 1 -> value =   51811
list[[3]] -> group 1 -> value =   ...
list[[4]] -> group 1 -> value =   ...
...
list[[100]] -> group 1 -> value = ...
                               -------
                                ∑ / 100



list[[1]] -> group 2 -> value =   50748 
list[[2]] -> group 2 -> value =   49165
list[[3]] -> group 2 -> value =   ...
list[[4]] -> group 2 -> value =   ...
...
list[[100]] -> group 2 -> value = ...
                               -------
                                ∑ / 100

我想计算每个组的算术值。 有没有办法做到这一点?

2 个答案:

答案 0 :(得分:3)

这是一个dplyr解决方案,它使用bind_rows()dfx折叠到单个数据帧中。

请注意,我在group中将您的group_ID列重命名为myfun()。原始dfx对象中的数据帧具有两个单独的列,都称为group

library(dplyr)

value <- c(1:1000)
group <- c(1:5)
df <- data.frame(value, group)

myfun <- function(){
  wz1 <- df[sample(nrow(df), size = 300, replace = FALSE),]
  wz2 <- df[sample(nrow(df), size = 10, replace = FALSE),]
  wz3 <- df[sample(nrow(df), size = 100, replace = FALSE),]
  wz4 <- df[sample(nrow(df), size = 40, replace = FALSE),]
  wz5 <- df[sample(nrow(df), size = 50, replace = FALSE),]

  wza <- rbind(wz1,wz2, wz3, wz4, wz5)
  wza_sum <- aggregate(wza, by = list(group_ID=wza$group), FUN = sum)
  return(wza_sum)
}

dfx <- replicate(100,myfun(),simplify = FALSE)

dfx_df <- bind_rows(dfx) %>% 
  group_by(group_ID) %>% 
  summarize(group_mean = mean(value))

结果

> head(dfx_df)
# A tibble: 5 x 2
  group_ID group_mean
     <int>      <dbl>
1        1     50064.
2        2     49806.
3        3     48814.
4        4     50051.
5        5     50972.

答案 1 :(得分:2)

还可以使用sample_n修改该函数以使其更简单

library(dplyr)
library(purrr)
myfun <- function(){map_dfr(c(300, 10, 100, 40, 50), ~ 
     df %>% 
        sample_n(.x)) %>% 
        group_by(group) %>% 
        summarise(value = sum(value))
  }

现在,我们使用rerun中的purrr,然后像其他解决方案一样绑定行

rerun(5, myfun()) %>% 
       bind_rows %>%
       group_by(group) %>%
       summarise(value = mean(value))