简体   繁体   English

产生重复的随机抽样

[英]generate repeated random sampling

I'm trying to generate a random sampling scheme for experiments I'm running this summer. 我正在尝试为今年夏天进行的实验生成随机抽样方案。 In this scheme, I'm doing four experimental trials for each bird nest at specific ages, at each site. 在此方案中,我正在每个地点针对特定年龄的每个燕窝进行四个实验。 The trials need to be random for each nest, but all nests must undergo all four different trials (ie, random order , not random trial type). 每个巢的试验必须是随机的,但是所有巢都必须经历所有四个不同的试验(即随机顺序 ,而不是随机试验类型)。

So far, I have: - a vector with the two site names repeated 80 times - a vector with the nests (20 potential nests/site) repeated 4 times - a vector with the ages (4 different periods) repeated 40 times 到目前为止,我有:-具有两个站点名称的向量重复了80次-具有嵌套的向量(每个站点20个潜在的嵌套)重复了4次-具有年龄(4个不同时期)的向量重复了40次

sites <- c(rep("AU", times = 80), rep("WE", times = 80)) 
nest <- c(rep(1:20, each = 4), rep(1:20, each = 4))
age <- rep(c("3/4", "7/8", "11/12", "15/16"), times = 40)df <- 

data.frame(cbind(sites, nest, age))
head(df)

  sites nest   age
1    AU    1   3/4
2    AU    1   7/8
3    AU    1 11/12
4    AU    1 15/16
5    AU    2   3/4
6    AU    2   7/8

For the last random sampling at each nest, I need to select trials 1 through 4. I've tried the following: 对于每个巢的最后一次随机抽样,我需要选择试验1到4。我尝试了以下方法:

trial <- rep(sample(1:4, 4, replace=FALSE), times = 40) #creates the same random order for each nest
trial <- rep(sample(1:4, 4, replace=FALSE), each = 40) #repeats the same number 40 times, before selecting the next one

How do I fix this? 我该如何解决?

Bonus points if you can help me set this up so that instead of having all trials in a single column, it's set up so that each trial is in a different column. 如果您可以帮助我设置奖励积分,则可以将所有试用设置在不同的栏中,而不是将所有试用都放在一个栏中。

The problem of generating a different order every time is solved with replicate . replicate可以解决每次生成不同订单的问题。 It will not repeat the same expression, it will call the expression expr n times. 它不会重复相同的表达式,它将调用表达式expr n次。

set.seed(1234)    # Make the results reproducible
trials1 <- replicate(40, sample(4))

To have the trials as columns, just transpose the results matrix. 要将试验作为列,只需转置结果矩阵即可。

trials2 <- t(trials1)
colnames(trials2) <- sprintf("trial_%02d", seq_len(ncol(trials2)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM