R 列出涵盖所有给定元素的所有字符串组合
假设给我以下字符串:R 列出涵盖所有给定元素的所有字符串组合,r,string,combinations,R,String,Combinations,假设给我以下字符串: 1:{a,b,c,t} 2:{b,c,d} 3:{a,c,d} 4:{a,t} 我想做一个程序,给我这些字符串的所有不同组合,其中每个组合必须包括每个给定的字母。 例如,上面的组合是字符串{1&2,1&3,2&3&4,1&2&3&4,2&4} 我在考虑使用for循环,程序将查看第一个字符串,找到缺少的元素,然后向下搜索列表,找到包含这些字母的字符串。然而,我认为这个想法只能找到两个字符串的组合,而且它还需要列出程序中的所有字母,这似乎非常不经济。作为一个开始。。。 我有时
1:{a,b,c,t}
2:{b,c,d}
3:{a,c,d}
4:{a,t}
我想做一个程序,给我这些字符串的所有不同组合,其中每个组合必须包括每个给定的字母。
例如,上面的组合是字符串{1&2,1&3,2&3&4,1&2&3&4,2&4}
我在考虑使用for循环,程序将查看第一个字符串,找到缺少的元素,然后向下搜索列表,找到包含这些字母的字符串。然而,我认为这个想法只能找到两个字符串的组合,而且它还需要列出程序中的所有字母,这似乎非常不经济。作为一个开始。。。
我有时间时会编辑这个答案。以下结果取决于选择的顺序。我还没有弄明白如何把名单平铺。如果我能将其展平,我会对每个结果进行排序,然后删除重复项
v = list(c("a","b","c","t"),c("b","c","d"),c("a","c","d"),c("a","t"))
allChars <- Reduce(union, v) # [1] "a" "b" "c" "t" "d"
charInList <- function(ch, li) which(sapply(li, function(vect) ch %in% vect))
locations <- sapply(allChars, function(ch) charInList(ch, v) )
# > locations
# $a
# [1] 1 3 4
#
# $b
# [1] 1 2
#
# $c
# [1] 1 2 3
#
# $t
# [1] 1 4
#
# $d
# [1] 2 3
findStillNeeded<-function(chosen){
haveChars <- Reduce(union, v[chosen])
stillNeed <- allChars[!allChars %in% haveChars]
if(length(stillNeed) == 0 ) return(chosen) #terminate if you dont need any more characters
return ( lapply(1:length(stillNeed), function(i) { #for each of the characters you still need
loc <- locations[[stillNeed[i]]] #find where the character is located
lapply(loc, function(j){
findStillNeeded(c(chosen, j)) #when you add this location to the choices, terminate if you dont need any more characters
})
}) )
}
result<-lapply(1:length(v), function(i){
findStillNeeded(i)
})
v=list(c(“a”、“b”、“c”、“t”)、c(“b”、“c”、“d”)、c(“a”、“c”、“d”)、c(“a”、“t”))
allChars我认为这样的方法应该行得通
sets <- list(c('a', 'b', 'c', 't'),
c('b', 'c', 'd'),
c('a', 'c', 'd'),
c('a', 't'))
combinations <- lapply(2:length(sets),
function(x) combn(1:length(sets), x, simplify=FALSE))
combinations <- unlist(combinations, FALSE)
combinations
# [[1]]
# [1] 1 2
#
# [[2]]
# [1] 1 3
#
# [[3]]
# [1] 1 4
#
# [[4]]
# [1] 2 3
#
# [[5]]
# [1] 2 4
#
# [[6]]
# [1] 3 4
#
# [[7]]
# [1] 1 2 3
#
# [[8]]
# [1] 1 2 4
#
# [[9]]
# [1] 1 3 4
#
# [[10]]
# [1] 2 3 4
#
# [[11]]
# [1] 1 2 3 4
u <- unique(unlist(sets))
u
# [1] "a" "b" "c" "t" "d"
Filter(function(x) length(setdiff(u, unlist(sets[x]))) == 0, combinations)
# [[1]]
# [1] 1 2
#
# [[2]]
# [1] 1 3
#
# [[3]]
# [1] 2 4
#
# [[4]]
# [1] 1 2 3
#
# [[5]]
# [1] 1 2 4
#
# [[6]]
# [1] 1 3 4
#
# [[7]]
# [1] 2 3 4
#
# [[8]]
# [1] 1 2 3 4
集合2和4不包括每个字母吗?还有1&2&3&4?是的,谢谢你指出我的错误。非常感谢,你能给我解释一下功能charInList的输入是什么吗?ie:ch和li是什么?回答得好,有没有办法编辑它,这样就不会把NA计算在列表中。例如,如果我让sets@user7512228可以使用集合在计算开始时删除缺少的值