how to create a for loop in R to run a simple random sample and calculate the average of each set

679 Views Asked by At
data = read.csv(file= "~/Downloads/data.csv")
temp=(data$temp)
n=75
N=length(temp)

s=sample(1:N, n)
ybar=mean(temp[s])

I want to run the sample 100 times where n is 75. Then calculate average of each sample, and subtract each average from a set number (50).

1

There are 1 best solutions below

0
On

Maybe a short loop is the way to go. Notice the bracket on the left-side of the equals sign in the last line of code - it's the key to using a loop for your calculation!

# set a seed - always a good idea when using randomness like 'sample()'
set.seed(123)

# pre-allocate an "empty" vector to fill in with results
ybar_vec = vector(length=n)

# do your calculation "n" times
for(i in 1:n) {
    s = sample(N)
    ybar_vec[i] = 50 - mean(temp[s]) # store i^th calc as i^th element of ybar_vec
}