This is for creating sampling design for my experiment. I want to survey 8 different individuals on every Monday of the year 2018. Order in which I survey them needs to be random for each Monday. For eg. A,B,C,D... for one Monday and then for next C,B,A,D....
To try this with R, I have a list of names: namelist<- ("A", "B", "C",...)
containing 8 different names. I want to assign these in random order to every Monday in a year. For this, I have created a list of dates for the entire year 2018. X<- ("01-01-2018", "02-01-2018",...)
and list of corresponding weekdays Y<- ("Monday", "Tuesday",...)
.
I need the entire namelist assigned in random order for all the Mondays in the year. What is the best way to go about it? Can I use for-loop for this? or is there another way to do this?
You can use the sample()
function in a for
loop to randomly sample from your name list into a dataframe:
Get all the Mondays in the year and create namelist:
dates = as.Date("2018-01-01") +7*(0:52)
namelist = c("A","B","C","D","E","F","G","H")
You've not specified how you want the output to look, but here is are two choices:
Multi Column approach:
samples=matrix(0,length(dates),length(namelist))
for(i in 1:length(dates)){samples[i,]=sample(namelist)}
df=data.frame(dates,samples)
> head(df)
dates X1 X2 X3 X4 X5 X6 X7 X8
1 2018-01-01 E G B D H C A F
2 2018-01-08 F D B C G H A E
3 2018-01-15 A E H D B C G F
4 2018-01-22 E C F H A D G B
5 2018-01-29 C E F B G H A D
6 2018-02-05 C G A H D F B E
Single Column approach:
df2 = data.frame(dates, samples_char="")
for(i in 1:nrow(df2)){df2[i,'samples_char']=paste0(sample(namelist),collapse=", ")}
> head(df2)
dates samples_char
1 2018-01-01 E, A, G, D, C, B, F, H
2 2018-01-08 B, E, F, A, C, H, G, D
3 2018-01-15 H, D, E, C, F, A, G, B
4 2018-01-22 G, F, A, D, E, H, C, B
5 2018-01-29 A, E, D, H, G, C, B, F
6 2018-02-05 C, H, G, F, E, B, D, A