tnt
tnt

Reputation: 1447

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 (i.e., 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

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:

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.

Upvotes: 0

Views: 163

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

The problem of generating a different order every time is solved with replicate. It will not repeat the same expression, it will call the expression expr n times.

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

Upvotes: 1

Related Questions