use*_*689 2 text loops r sample
我从包含许多值列表的文件中提取样例,例如:
312313.34
243444
12334.92
321312
353532
Run Code Online (Sandbox Code Playgroud)
并使用R从该列表中随机抽样:
list = read.table("data")
out <-sample(list,50,replace=TRUE)
out.mean<-mean(out)
out.mean
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我如何把它放到一个循环中,这样我就可以执行1000次这个程序并取1000的平均值意味着这会产生吗?
非常感谢你提前!
Rubal
另一种解决方案可能是(记住@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)))
Run Code Online (Sandbox Code Playgroud)
对于每个大小为50的子样本,均值由1000个均值组成.如果您想要均值,请执行以下操作:
mean(Means)
Run Code Online (Sandbox Code Playgroud)
你正在尝试做的事情听起来像一个自举或类似于重新采样技术的偏差减少(我猜).
我会从采样中做出一个函数,然后一遍又一遍地重复一遍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)
Run Code Online (Sandbox Code Playgroud)