1

I would like to extract all possible subsequences from a vector of length n. For example if I have c("a","b","c") I would like to find c("a","b","c","ab","ac","bc","abc",""). I can solve this manually with vector of short lengths but the problem becomes intractable with longer lengths. Any idea how I can do this using some iteration?

1 Answers1

1

Using combn.

x <- c("a","b","c")

unlist(sapply(1:length(x), function(i) combn(x, i, simplify=F)), recursive=F)
# [[1]]
# [1] "a"
# 
# [[2]]
# [1] "b"
# 
# [[3]]
# [1] "c"
# 
# [[4]]
# [1] "a" "b"
# 
# [[5]]
# [1] "a" "c"
# 
# [[6]]
# [1] "b" "c"
# 
# [[7]]
# [1] "a" "b" "c"

Or

unlist(sapply(1:length(x), function(i) combn(x, i, function(j) Reduce(paste0, j))))
# [1] "a"   "b"   "c"   "ab"  "ac"  "bc"  "abc"
jay.sf
  • 60,139
  • 8
  • 53
  • 110