简体   繁体   English

为随机抽样构建 R 循环

[英]building an R loop for random sampling

I am sampling from a file containing a list of many values eg:我正在从一个包含许多值列表的文件中采样,例如:

312313.34
243444
12334.92
321312
353532

and using R to randomly sample from this list:并使用 R 从此列表中随机抽样:

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

Could somebody please show me how to put this into a loop, so that I can perform this procedure 1000 times and take the mean of the 1000 means that this will generate?有人可以告诉我如何将其放入循环中,以便我可以执行此过程 1000 次并取这将生成的 1000 次的平均值吗?

Thank you very much in advance!非常感谢您提前!

Rubal鲁巴尔

An alternative solution could be (keep in mind what @Tyler Rinker just said about replicate )另一种解决方案可能是(请记住@Tyler Rinker 刚才所说的关于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))) 

Means consists of 1000 mean each one for every subsample of size 50. If you want the mean of the means do this:对于每个大小为 50 的子样本,均值由 1000 个均值组成。如果您想要均值的均值,请执行以下操作:

mean(Means) 

What you're trying to do sounds like a bootstrapping or something similar to resample techniques for bias reduction (I guess).您尝试做的事情听起来像是引导或类似于减少偏差的重新采样技术(我猜)。

I'd make a function out of the sampling and then repeat that over and over with lapply (though replicate would likely work too I've had experiences with this being much slower)我会从采样中创建一个函数,然后用lapply重复该lapply (尽管replicate也可能起作用,但我有过这种速度慢得多的经验)

I'd recommend not write to an object named list as this is an important function.我建议不要写入名为list的对象,因为这是一个重要的函数。

So it would look something like this:所以它看起来像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM