2012-08-26 55 views
2

我从含有许多值的列表的文件采样的R循环,例如:构建为随机采样

312313.34 
243444 
12334.92 
321312 
353532 

和,使用R随机地从该列表中进行采样:

list = read.table("data") 
out <-sample(list,50,replace=TRUE) 
out.mean<-mean(out) 
out.mean 

可能有人请告诉我如何将它放入一个循环中,以便我可以执行此过程1000次,并采用这意味着这将产生的意思?

非常感谢您提前!

Rubal

+0

[from given distribution](http://stackoverflow.com/questions/12128996/sample-from-given-distribution) – Andrie

回答

7

另一种解决方案可能是(记住什么@Tyler林克刚才关于replicate

Data <- read.table(text=' 
312313.34 
243444 
12334.92 
321312 
353532', header=FALSE) 

Data <- as.numeric(as.matrix((Data))) 

set.seed(007) 
Means <- replicate(1000, mean(sample(Data,50,replace=TRUE))) 

手段包括1000平均每一个用于大小为50的每个子样本。如果您想要这样做的意思是:

mean(Means) 

你试图做的事情听起来像一个引导或类似的重采样技术偏见减少(我猜)。

5

我会成为一个功能出了取样,然后重复一遍又一遍地用lapply(虽然replicate可能会工作太我有经验,这个是慢得多)

我建议不要写入名为list的对象,因为这是一个重要功能。

因此,这将是这个样子:

#make a data set that may look like yours 
LIST <- rnorm(1000) 

#take your code and make a function 
mean.find <- function(dat) { 
    out <-sample(dat, 50,replace=TRUE) 
    mean(out) 
} 

#a single use yo check it out 
mean.find(LIST) 

#repeat it 1000 times with lapply 
reps <- unlist(lapply(seq_len(1000), mean.find)) 

#take the mean of that 
mean(reps) 
+0

+1和一些挑剔;)。函数“mean.find”有一个不使用的输入参数:'dat'。最好是要么忽略它,要么用'out <-sample(dat,50,replace = TRUE)'。这使得函数更一般化,你可以为任何数据集获得50个样本,代码不依赖于找到全局变量calldd'LIST'的范围。 –

+0

@保罗良好的捕获,这是我的意图,但我从未贯彻过。我按照你的建议做了编辑。 'nitpicking = growth':D –

+0

从函数内部使用全局对象会让我有点不安,尽管我非常使用它。简而言之,风险可能很小,但在较大的项目中可能会导致不可预测的行为。 –