创建组合列表并删除预先使用的组合

时间:2016-12-14 18:28:58

标签: r combinations permutation

在R下,我一直在尝试生成颜色组合,在此之后我想导入预先使用的组合,删除所有可能的组合,最后导出可用的组合。我很难删除这些预先使用过的。谢谢你的帮助! 祝一切顺利, - 卡洛斯

rm(list=ls());ls()
library("gtools")

# Generate all colors combinations
colors<-c("RED","GREEN","BLUE","BLACK","PINK")
size.of.combinations<-4
all.possible.combinations<-permutations(length(colors),size.of.combinations,colors,repeats.allowed=T)

# Import used data
used.comb<- read.table(file = "used.txt", header = TRUE);   
used.comb<-as.matrix(used.comb)

# Removed pre-used combinations
comb.available<-all.possible.combinations-used.comb #here is the problem

my.data<-data.frame(comb.available)
write.table(my.data, file = "data.csv", sep = ",", col.names = NA, qmethod = "double")

1 个答案:

答案 0 :(得分:1)

用这个删除预先使用的组合,它应该可以正常工作(其他行是可以的)。

# Removed pre-used combinations
comb.available<- 
             do.call(rbind, strsplit(setdiff(
               apply(all.possible.combinations, 1, function(x) paste(x, collapse=',')), 
               apply(used.comb, 1, function(x) paste(x, collapse=','))), split=','))   #this should work fine