【问题标题】:R calculate the standard error using bootstrapR使用引导程序计算标准误差
【发布时间】:2013-08-22 21:20:10
【问题描述】:

我有这个值数组:

> df
[1] 2 0 0 2 2 0 0 1 0 1 2 1 0 1 3 0 0 1 1 0 0 0 2 1 2 1 3 1 0 0 0 1 1 2 0 1 3
[38] 1 0 2 1 1 2 2 1 2 2 2 1 1 1 2 1 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 1 0 0 0 0 0
[75] 0 0 0 0 0 1 1 0 1 1 1 1 3 1 3 0 1 2 2 1 2 3 1 0 0 1

我想使用包启动来计算数据的标准误差。 http://www.ats.ucla.edu/stat/r/faq/boot.htm

于是,我就用这个命令追了上去:

library(boot)
boot(df, mean, R=10)

我得到了这个错误:

Error in mean.default(data, original, ...) : 
'trim' must be numeric of length one

有人可以帮我解决问题吗?谢谢

【问题讨论】:

  • c 的函数定义是什么?基础c 函数不适合自举。

标签: r standard-error statistics-bootstrap


【解决方案1】:

如果您要引导均值,您可以执行以下操作:

set.seed(1)
library(boot)
x<-rnorm(100)
meanFunc <- function(x,i){mean(x[i])}
bootMean <- boot(x,meanFunc,100)
>bootMean

ORDINARY NONPARAMETRIC BOOTSTRAP


Call:
boot(data = x, statistic = meanFunc, R = 100)


Bootstrap Statistics :
     original      bias    std. error
t1* 0.1088874 0.002614105  0.07902184

如果您只是输入 mean 作为参数,您将收到与您得到的错误类似的错误:

bootMean <- boot(x,mean,100)
Error in mean.default(data, original, ...) : 
  'trim' must be numeric of length one

【讨论】:

    【解决方案2】:

    我从来没有真正使用过 boot,因为我不明白它会带来什么。

    鉴于标准误差定义为:

    sd(sampled.df) / sqrt(length(df))

    我相信您可以简单地使用以下函数来完成这项工作:

    custom.boot <- function(times, data=df) {
      boots <- rep(NA, times)
      for (i in 1:times) {
        boots[i] <- sd(sample(data, length(data), replace=TRUE))/sqrt(length(data))  
      }
      boots
    }
    

    然后您可以自己计算期望值(因为您得到了一些样本实现的分布):

    # Mean standard error
    mean(custom.boot(times=1000))
    [1] 0.08998023
    

    若干年后……

    我觉得这样更好:

    mean(replicate(times, sd(sample(df, replace=T))/sqrt(length(df))))
    

    【讨论】:

      【解决方案3】:

      函数c 不足以满足boot。如果您查看boot 的帮助,您会看到您的函数必须能够接收数据和索引。因此,您需要编写自己的函数。此外,它应该返回您想要标准误差的值,例如平均值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-20
        • 1970-01-01
        • 2015-01-09
        • 2016-04-24
        相关资源
        最近更新 更多