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:
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?
Thank you very much in advance!
Rubal
An alternative solution could be (keep in mind what @Tyler Rinker just said about 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:
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)
I'd recommend not write to an object named list as this is an important function.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With