1

I have a vector

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

with splitted entries

str_split(x, " ")

I want to get all permutations per splitted vector entry, so the result should be

c("a b c", "b c a", "c a b", "a c b", "b a c", "c b a", "d e", "e d")

I tried to use function

permutations(n, r, v=1:n, set=TRUE, repeats.allowed=FALSE)
Judy
  • 35
  • 5
  • 1
    Related, possible duplicate https://stackoverflow.com/q/22569176/680068 – zx8754 Sep 14 '20 at 08:55
  • 1
    Another related/possible duplicate : https://stackoverflow.com/q/11095992/4137985 – Cath Sep 14 '20 at 12:08
  • Does this answer your question? [Generating all distinct permutations of a list in R](https://stackoverflow.com/questions/11095992/generating-all-distinct-permutations-of-a-list-in-r) – Joseph Wood Dec 05 '20 at 05:19

2 Answers2

4

After the str_split step , you can use combinat::permn to create all possible permutation of the string and paste them together.

result <- unlist(sapply(strsplit(x, " "), function(x) 
                 combinat::permn(x, paste0, collapse = " ")))
result
#[1] "a b c" "a c b" "c a b" "c b a" "b c a" "b a c" "d e"   "e d"  
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

You can try pracma::perms like below

unlist(
  Map(
    function(v) do.call(paste, as.data.frame(pracma::perms(v))),
    strsplit(x, " ")
  )
)

which gives

[1] "c b a" "c a b" "b c a" "b a c" "a b c" "a c b" "e d"   "d e"
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81