Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

building an R loop for random sampling

Tags:

text

loops

r

sample

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

like image 810
user964689 Avatar asked Dec 21 '25 11:12

user964689


2 Answers

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

like image 72
Jilber Urbina Avatar answered Dec 23 '25 00:12

Jilber Urbina


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)
like image 44
Tyler Rinker Avatar answered Dec 23 '25 01:12

Tyler Rinker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!