组合搜索字符向量

时间:2018-10-04 02:10:32

标签: r pattern-matching character combinations permutation

a<-c('a','b','c','d')

需要将其组合在一起

必需的输出是

(a b c d,a b c,b c d,a b,b c,c d,a,b,c,d)

2 个答案:

答案 0 :(得分:1)

我将@ chinsoon12建议与另外的paste结合使用来获得所需的输出:

paste(lapply(unlist(lapply(rev(seq_along(a)), function(m) combn(a, m, simplify=FALSE)), recursive=FALSE), paste, collapse=" "), collapse=",")

返回: “ a b c d,a b c,a b d,a c d,b c d,a b,a c,a d,b c,b d,c d,a,b,c,d”

答案 1 :(得分:0)

可以从c('a', 'b', 'c', 'd') = letters[1:4]的{​​{3}}构建所需的输出。使用powerset库中的rje函数,我们可以:

unlist(lapply(rje::powerSet(letters[1:4])[-1], paste0, collapse = ' '))
[1] "a"       "b"       "a b"     "c"       "a c"     "b c"     "a b c"  
[8] "d"       "a d"     "b d"     "a b d"   "c d"     "a c d"   "b c d"  
[15] "a b c d"