Quan Mai
Quan Mai

Reputation: 11

Sampling with restriction in R

I have to create a profile with 3 characteristics that is a combination of these 3 lists:

Char1<-c("a1","a2","a3")
Char2<-c("b1","b2","b3")
Char3<-c("c1","c2")

A profile would look something like: [“a1”, “b2” , “c2”] or [“a3”,”b1”,”c1”]. I have a total of 18 profiles. The list of profiles is L:

L<-unique(do.call(c, apply(expand.grid(Char1,Char2,Char3), 1, combn, m=3, simplify=FALSE)))

> length(L)

[1] 18

> sample(L,3,replace=FALSE) # sample of 3 profiles from the list of 18

[[1]]
Var1 Var2 Var3 
"a2" "b2" "c1" 

[[2]]
Var1 Var2 Var3 
"a1" "b1" "c1" 

[[3]]
Var1 Var2 Var3 
"a3" "b2" "c2" 

I want to take out 2 profiles from the pool of 18 profiles so that:

I want to do this a 100 times. How do I wrote a loop that return 100 pairs that satisfy such restriction?

Thank you for your help,

Upvotes: 0

Views: 732

Answers (1)

adaien
adaien

Reputation: 1942

samples<-lapply(1:100,function(i){
profile1<-c(Char1[sample(1:3,1)],Char2[sample(1:3,1)],Char3[sample(1:2,1)])
profile2<-c()
profile2[1]<-ifelse(profile1[1]=="a1",sample(c("a2","a3"),1),Char1[sample(1:3,1)])
profile2[2]<-ifelse(profile1[2]=="b2",sample(c("b1","b3"),1),Char2[sample(1:3,1)])
profile2[3]<-ifelse(profile1[3]=="c1","c2",Char3[sample(1:2,1)])
list(profile1,profile2)  
})

Upvotes: 0

Related Questions