【问题标题】:how to create a for loop in R to run a simple random sample and calculate the average of each set如何在 R 中创建一个 for 循环来运行一个简单的随机样本并计算每个集合的平均值
【发布时间】:2021-05-24 23:57:31
【问题描述】:
data = read.csv(file= "~/Downloads/data.csv")
temp=(data$temp)
n=75
N=length(temp)

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

我想运行样本 100 次,其中 n 为 75。然后计算每个样本的平均值,并从一组数字 (50) 中减去每个平均值。

【问题讨论】:

    标签: r loops sampling srs


    【解决方案1】:

    也许一个短循环是要走的路。请注意最后一行代码中等号左侧的括号 - 这是使用循环进行计算的关键!

    # 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
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-16
      • 1970-01-01
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多