2013-08-20 78 views
8

我有此数组的值:ř计算标准误差

> 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 

有人可以帮我找出这个问题?谢谢

+1

什么是'C'你的函数定义?基地'c'功能不适合自举。 – Frank

回答

11

如果你是自举的意思是你可以做如下:

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 
1

功能c是不够的boot。如果你看boot的帮助,那么你会发现你的函数必须能够接收数据和索引。所以,你需要编写你自己的功能。此外,它应该返回您想要的标准误差的值,如平均值。

3

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

鉴于标准误差定义为:

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))))