使用R代码“sample”函数,取出500个观察值的10个随机样本

时间:2017-09-17 14:20:15

标签: r

最简单的方法 - 使用R代码sample功能,从每个10000 rnorm中取出500个观察值的10个随机样本。计算每个样本的平均值。然后计算样本均值的均值和样本均值的标准差。

2 个答案:

答案 0 :(得分:1)

#take out 10 random samples of 500 observations from the 10000 rnorm each. 

s0 <- sample(rnorm(10000),500)
s1 <- sample(rnorm(10000),500)
s2 <- sample(rnorm(10000),500)
s3 <- sample(rnorm(10000),500)
s4 <- sample(rnorm(10000),500)
s5 <- sample(rnorm(10000),500)
s6 <- sample(rnorm(10000),500)
s7 <- sample(rnorm(10000),500)
s8 <- sample(rnorm(10000),500)
s9 <- sample(rnorm(10000),500)

#Calculate the mean of each sample. 
c(mean(s0),mean(s1), mean(s2), mean(s3),
  mean(s4), mean(s5), mean(s6), mean(s7),
  mean(s8), mean(s9))
 [1]  0.028727024 -0.017773740 -0.022705430 -0.001933892  0.045273423  0.009788866  0.004833384  0.018486670  0.007363636  0.017806898
#Then calculate the mean of the sample means 
mean(c(mean(s0),mean(s1), mean(s2), mean(s3),
       mean(s4), mean(s5), mean(s6), mean(s7),
       mean(s8), mean(s9))
)
  

[1] 0.008986684

# standard deviation
sd(c(mean(s0),mean(s1), mean(s2), mean(s3),
       mean(s4), mean(s5), mean(s6), mean(s7),
       mean(s8), mean(s9))
)
  

[1] 0.02037087

答案 1 :(得分:0)

使用replicate重复sample/rnorm来电。

set.seed(1435)   # Make it reproducible

r <- replicate(10, sample(rnorm(1e4), 500))
(m <- colMeans(r))
#[1]  0.058202386  0.013195277 -0.031991121  0.026903820 -0.008564268
#[6] -0.017718631  0.001395289  0.032600240 -0.045317892  0.086021587

(M <- mean(m))
#[1] 0.01147267

(s <- sd(m))
#[1] 0.04068593