使用R循环计算随机子样本的统计数据

时间:2015-06-15 18:02:57

标签: r for-loop subsampling

我试图在R中找到一种方法来随机分配一些数据(用于生态研究的区域中适当栖息地的比例),计算具有值> 1的样本的平均值和比例。 0然后将这些值保存或追加到数据框。然后我想多次重复一遍(例如1000)。标准自举或重采样包不起作用,因为我需要计算出现频率以及子样本的均值。我知道“应用”函数,但是那些循环遍及整个数据框,而我试图在重复的子样本上进行。我知道我需要一些代码来获取循环中的计算值以保存和输出但有问题。 “habprop”是数据框(“数据”)中的一列,我想计算和保存的正值的平均值和比例。

for(i in 1000 {  
randsample=data[sample(1:nrow(data), 50, replace=FALSE),]
m=mean(randsample$habprop)
randsamplepos=subset(randsample, habprop > 0)
habfreq=(nrow(randsamplepos)/nrow(randsample))
})

2 个答案:

答案 0 :(得分:1)

replicate功能怎么样? This post看起来很相似。

生成一些数据以便

data <- data.frame(x1=rpois(5000, 5), x2=runif(5000), x3=rnorm(5000))

定义一个采样功能并采取手段和计数

sample_stats <- function(df, n=100){
  df <- df[sample(1:nrow(df), n, replace=F),]
  mx1 <- mean(df$x1[df$x1>0])
  x1pos <- sum(df$x1>0)
  return(c(mx1, x1pos))
}

运行一次只是为了看输出

sample_stats(data)

运行1000次

results <- replicate(1000, sample_stats(data, n=100))

答案 1 :(得分:0)

使用boot这应该是可能的

dat <- data.frame(habprop=rnorm(100))

## Function to return statistics from subsamples
stat <- function(dat, inds)
    with(dat, c(mu=mean(habprop[inds]), freq=sum(habprop[inds] > 0)/length(inds)))

library(boot)
boot(data=dat, statistic=stat, R=1000)

# Bootstrap Statistics :
#        original      bias    std. error
# t1* -0.06154533 -0.00324393  0.08377116
# t2*  0.52000000 -0.00073000  0.04853991
相关问题