3

我在理解如何dplyr bootstrap正确使用该功能时遇到问题。

我想要的是从两个随机分配的组中生成引导分布并计算均值的差异,例如:

library(dplyr) 
library(broom) 
data(mtcars) 

mtcars %>% 
  mutate(treat = sample(c(0, 1), 32, replace = T)) %>% 
  group_by(treat) %>%
  summarise(m = mean(disp)) %>% 
  summarise(m = m[treat == 1] - m[treat == 0])

问题是我需要重复此操作100,1000或更多次。

使用replicate,我可以做到

frep = function(mtcars) mtcars %>% 
  mutate(treat = sample(c(0, 1), 32, replace = T)) %>% 
  group_by(treat) %>%
  summarise(m = mean(disp)) %>% 
  summarise(m = m[treat == 1] - m[treat == 0])

replicate(1000, frep(mtcars = mtcars), simplify = T) %>% unlist()

并得到分布

在此处输入图像描述

我真的不知道如何在bootstrap这里使用。我应该如何开始?

mtcars %>% 
  bootstrap(10) %>% 
  mutate(treat = sample(c(0, 1), 32, replace = T)) 

mtcars %>% 
  bootstrap(10) %>% 
  do(tidy(treat = sample(c(0, 1), 32, replace = T))) 

它并没有真正起作用。我应该把bootstrap点子放在哪里?

谢谢。

4

1 回答 1

2

在这一步中,我们用'treat' 列do包装并创建,然后我们可以按 'replicate' 和 'treat' 分组以获得d 输出列data.framesummarise

mtcars %>% 
    bootstrap(10) %>% 
    do(data.frame(., treat = sample(c(0,1), 32, replace=TRUE))) %>% 
    group_by(replicate, treat) %>% 
    summarise(m = mean(disp)) %>%
    summarise(m = m[treat == 1] - m[treat == 0])
    #or as 1 occurs second and 0 second, we can also use
    #summarise(m = last(m) - first(m))
于 2016-09-17T16:25:41.863 回答