r - 分层/嵌套引导方法
问题描述
我正在尝试执行分层引导,以从具有嵌套数据结构的大型数据集中获取一些样本均值。
我有一个与此类似的数据集:
ball <- c(1:13)
box <- c('1', '1', '1', '1', '2', '2', '2',
'3', '3', '3', '3', '3', '3')
triangles <- c(1,0,1,3,1,1,2,2,0,1,1,0,4)
df <- data.frame(cbind(ball, box, triangles))
df
--
ball box triangles
1 1 1
2 1 0
3 1 1
4 1 3
5 2 1
6 2 1
7 2 2
8 3 2
9 3 0
10 3 1
11 3 1
12 3 0
13 3 4
这个想法是有三个盒子,每个盒子里都有很多球。每个球上都有许多三角形,看起来像这样:
我的目标是,使用自举法来估计每个球上三角形的平均数量,同时控制球在哪个盒子里。
我希望模拟从盒子中进行 10,000 次替换抽样,每次随机拉一个盒子,然后随机抽样 n 次替换,其中 n 是盒子中的球数(即如果盒子 1 被选中,那么模拟将对这四个球进行四次随机抽样,最终得到任意数量的响应,例如第 1 球、第 1 球、第 3 球、第 4 球)。
然后我希望它计算它采样的球上三角形数量的平均值,存储该值,然后对一个新盒子进行采样,从而重复该过程。
到目前为止,我已经尝试使用这样的 rsample 方法(在此处描述:) :
#we need to sample groups aka boxes from
#the dataframe so use list-columns in
#tibbles
library(tidyverse)
library(tibble)
library(rsample)
Test <- df %>% nest(-box)
head(Test)
#now use bootstraps on this new tibble to
#sample by ID
set.seed(002)
testbs <- bootstraps(Test, times = 10)
testbs
#let's look at one of the bootstrap
#samples
as_tibble(testbs$splits[[1]]) %>% head()
#we can unnest the tibble and assess the
#averages by box
bs_avgtri<- map(testbs$splits,
~as_tibble(.) %>% unnest() %>%
group_by(box) %>%
summarize(mean_tri =
mean(triangles))) %>%
bind_rows(.id = 'boots')
bs_avgtri
但是,我认为这是有缺陷的,因为我嵌套数据的方式。我得到的输出也没有意义,通常显示多个引导级别。所以我倾向于认为它出了问题,但我也不确定如何真正解析出不同函数在做什么。
我也知道我借用的方法并不真正适用于我正在做的事情,我正在尝试一种方法来做这件事,我不认为它在做我需要做的事情。
我能想到的唯一另一种方法是编写几个嵌套的 for 循环,但我不擅长 R 中的 for 循环,我相当确定有更好的方法。
如果有人对此有任何见解,我将非常感激!!!!
解决方案
tidyr::crossing
对于模拟来说非常方便。
library("tidyverse")
ball <- c(1:13)
box <- c('1', '1', '1', '1', '2', '2', '2',
'3', '3', '3', '3', '3', '3')
triangles <- c(1,0,1,3,1,1,2,2,0,1,1,0,4)
df <- tibble(ball, box, triangles)
df %>%
# How many times do you want to run the simulation?
crossing(rep = seq(3)) %>%
# Next describe the sampling.
# For each simulation and for each box...
group_by(rep, box) %>%
# randomly sample n() balls with replacement,
# where n() is the number of balls in the box.
sample_n(n(), ball, replace = TRUE) %>%
# Compute the mean number of triangles (for each replicate, for each box)
summarise(triangles = mean(triangles))
#> # A tibble: 9 x 3
#> # Groups: rep [3]
#> rep box triangles
#> <int> <chr> <dbl>
#> 1 1 1 1.5
#> 2 1 2 1.67
#> 3 1 3 2
#> 4 2 1 2
#> 5 2 2 1.33
#> 6 2 3 1.33
#> 7 3 1 2
#> 8 3 2 1.67
#> 9 3 3 1.5
由reprex 包(v0.2.1)于 2019 年 3 月 4 日创建
推荐阅读
- javascript - 错误:products.map 不是函数 Mern Stack
- asp.net-core - 如何在不按 CTRL 键的情况下使用 ASP.NET 在选择元素中选择多个项目?
- java - 我在这个程序中遇到了一个排序问题,帮我解决这个问题
- c++ - 为所有 clion 项目包含相同的头文件
- javascript - 对于模型 \"USER\" 的路径 \"_id\" 中的值 \"post\"(类型字符串),转换为 ObjectId 失败
- react-native - 博览会退出后不会发布apk
- swift - Swift 中自动调整大小的集合视图单元格
- html - 是否可以在 HTML 中将字母屏蔽为空格?在这种情况下,我想将 UNDERSCORE(_) 屏蔽为空格
- c++ - Qt 和 C++:斜线、水平线和垂直线
- android - 如何让 Jetpack 组合 IconButton 的宽度以适应儿童的宽度?