【问题标题】:Sampling with restriction in R在 R 中进行限制采样
【发布时间】:2016-03-21 22:59:24
【问题描述】:

我必须创建一个具有 3 个特征的配置文件,它是这 3 个列表的组合:

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

配置文件类似于:[“a1”, “b2”, “c2”] 或 [“a3”,”b1”,”c1”]。我总共有 18 个配置文件。配置文件列表是 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" 

我想从 18 个配置文件池中取出 2 个配置文件,以便:

  • 第一个配置文件没有限制,可以是 18 个配置文件中的任何一个。

  • 对于第二个配置文件,

    • 如果第一个配置文件的 Char1 是“a1”,则第二个配置文件的 Char1 只能是“a2”或“a3”

    • 如果第一个配置文件的 Char2 是“b2”,则第二个配置文件的 Char2 只能是“b1”或“b3”

    • 如果第一个配置文件的 Char3 为“c1”,则第二个配置文件的 Char3 只能为“c2”。

我想这样做 100 次。 如何编写一个返回 100 对满足此类限制的循环?

感谢您的帮助,

【问题讨论】:

    标签: r sample sampling random-sample


    【解决方案1】:
    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)  
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多