Create Combinations in R by Groups

后端 未结 7 1074
一整个雨季
一整个雨季 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 19:40

    This code below works.

    # Create list of the 20 records
    list <- c(1:20)
    
    # Generate all combinations including repetitions
    c <- data.frame(expand.grid(rep(list(list), 4))); rm(list)
    c$combo <- paste(c$Var1, c$Var2, c$Var3, c$Var4)
    # Remove repetitions
    c <- subset(c, c$Var1 != c$Var2 & c$Var1 != c$Var3 & c$Var1 != c$Var4 & c$Var2 != c$Var3 & c$Var2 != c$Var4 & c$Var3 != c$Var4)
    
    # Create common group labels (ex. abc, acb, bac, bca, cab, cba would all have "abc" as their group label).
    key <- data.frame(paste(c$Var1, c$Var2, c$Var3, c$Var4))
    key$group  <- apply(key, 1, function(x) paste(sort(unlist(strsplit(x, " "))), collapse = " "))
    c$group <- key$group; rm(key)
    
    # Sort by common group label and id combos by group
    c <- c[order(c$group),]
    c$Var1 <- NULL; c$Var2 <- NULL; c$Var3 <- NULL; c$Var4 <- NULL;
    c$rank <- rep(1:24)
    
    # Pivot
    c <- reshape(data=c,idvar="group", v.names = "combo", timevar = "rank", direction="wide")
    

提交回复
热议问题