Create Combinations in R by Groups

后端 未结 7 1086
一整个雨季
一整个雨季 2021-02-08 19:23

I want to create a list for my classroom of every possible group of 4 students. If I have 20 students, how I can I create this, by group, in R where my rows are each combination

7条回答
  •  渐次进展
    2021-02-08 20:00

    So you could get all the combinations with the expand.grid function just adding the vector of data four times. Then the result will have combinations like c(1,1,1,1) so i remove each row that have any duplicated value and the last part is just making the combinations. It is 2 loops and it is quite slow but it will get what you want. It could be speed up with the Rcpp package. The code is:

    ids = 1:20
    d2 = expand.grid(ids,ids,ids,ids)
    ## Remove rows with duplicated values
    pos_use = apply(apply(d2,1,duplicated),2,function(x) all(x == F))
    d2_temp = t(apply(d2[pos_use,],1,sort))
    list_temp = list()
    pos_quitar = NULL
    for(i in 1:nrow(d2_temp)){
      pos_quitar = c(pos_quitar,i)
      ini_comb = d2_temp[i,]
      d2_temp_use  = d2_temp[-pos_quitar,]
      temp_comb = ini_comb
      for(j in 2:5){
        pos_quitar_new = which(apply(d2_temp_use,1,function(x) !any(temp_comb%in%x)))[1]
        temp_comb = c(temp_comb,d2_temp_use[pos_quitar_new,])
      }
      pos_quitar = c(pos_quitar,pos_quitar_new)
      list_temp[[i]] = temp_comb
    }
    
    list_temp
    

提交回复
热议问题