【发布时间】:2020-07-19 11:22:16
【问题描述】:
我目前正在尝试对一些数据进行引导分析,最终结果是获得围绕计数数据比例的引导置信区间。
例如,我正在尝试引导的当前数据将采用以下形式(字符):
> foo
notes
1 a
2 b
3 c
4 c
5 b
6 c
7 b
8 c
9 a
10 a
11 c
12 b
13 d
14 e
15 f
16 f
17 g
18 a
19 b
20 c
21 c
你可以通过dput()获得这里
structure(list(notes = c("a", "b", "c", "c", "b", "c", "b", "c",
"a", "a", "c", "b", "d", "e", "f", "f", "g", "a", "b", "c", "c"
)), class = "data.frame", row.names = c(NA, -21L))
在尝试设置一个函数,该函数将输出类似于boot package 正常运行所需的命名向量(参见示例here),我编写了以下使用dplyr 代码的函数:
library(dplyr)
notes_bootstrap <- function(d, i){
# get global set
global_set <- d %>% distinct()
# take random rows
sampler <- d#[i,]
proportion_table <- sampler %>%
count(.data$notes) %>%
mutate(proportion = n/sum(n)) %>%
ungroup()
# combine with full set to turn NAs to 0s
combined_table <- proportion_table %>% full_join(global_set)
final_table <- combined_table %>%
select(-n) %>%
mutate(proportion = if_else(is.na(proportion),0,proportion))
output <- setNames(final_table$proportion, final_table$notes)
return(output)
}
当这个版本的函数使用boot() 运行时,它运行得很好,关键问题是它只是对整个数据集进行采样(由于代码的注释部分而没有执行引导程序)。如果你运行这个,你会看到每个估计都是一样的。
bootstrap_analysis <- boot(foo, notes_bootstrap, R = 100)
bootstrap_analysis$t
如果我确实使用为引导分析随机子集变量的部分运行该函数,如下面的代码所示(与上面相同,但删除了注释):
notes_bootstrap <- function(d, i){
# get global set
global_set <- d %>% distinct()
# take random rows
sampler <- d[i,]
proportion_table <- sampler %>%
count(.data$notes) %>%
mutate(proportion = n/sum(n)) %>%
ungroup()
# combine with full set to turn NAs to 0s
combined_table <- proportion_table %>% full_join(global_set)
final_table <- combined_table %>%
select(-n) %>%
mutate(proportion = if_else(is.na(proportion),0,proportion))
output <- setNames(final_table$proportion, final_table$notes)
return(output)
}
然后我得到以下错误:
> bootstrap_analysis <- boot(foo, notes_bootstrap, R = 100)
Error in UseMethod("group_by_") :
no applicable method for 'group_by_' applied to an object of class "character"
该问题的解决方案是运行此代码,以便引导分析按书面方式工作(可能是一个整洁的评估问题?),或者让某人提出一种更有效的方法来进行此引导分析。
【问题讨论】:
-
sampler <- d[i,, drop = FALSE]。提取默认简化为尽可能少的维度,并且由于d只是一列,d[i,]的结果是字符向量,而不是 df。此外,在引导时,设置 RNG 种子以使结果可重现,set.seed(<integer>)。