0

Suppose i have several values

d1,d2,d3,d4,d5

How can I swap them in this format?

d2,d1,d3,d4,d5
d3,d2,d1,d4,d5
d4,d1,d2,d3,d5
d5,d1,d2,d3,d4.

In other words, each subsequent value from a series of values ​​becomes the first, and other, in order, follow it. When there are few values, i can do it manually, but if there are hundreds of them, it is much more difficult. Any help is appreciated. Thank you.

psysky
  • 3,037
  • 5
  • 28
  • 64
  • 1
    Do you want all permutations of a vector? https://stackoverflow.com/questions/14704039/r-generate-all-permutations-of-vector-without-duplicated-elements – Ronak Shah Jan 29 '22 at 10:42

3 Answers3

1

I see that you don't want all permutations or even all possible n-way combinations. Here is one way to do it.

x <- c("d1","d2","d3","d4","d5")
t(sapply(1:length(x), function(i)x[c(i, (1:length(x))[-i])]))
#     [,1] [,2] [,3] [,4] [,5]
# [1,] "d1" "d2" "d3" "d4" "d5"
# [2,] "d2" "d1" "d3" "d4" "d5"
# [3,] "d3" "d1" "d2" "d4" "d5"
# [4,] "d4" "d1" "d2" "d3" "d5"
# [5,] "d5" "d1" "d2" "d3" "d4"
DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25
1

Something "fun" to try using SOfun package. Result left as a list.

# source("http://news.mrdwab.com/install_github.R")
# install_github("mrdwab/SOfun")

library(SOfun)

vec <- paste0("d", 1:5)

sapply(
  vec,
  \(x) moveMe(vec, paste(x, "first")),
  simplify = F
)

Output

$d1
[1] "d1" "d2" "d3" "d4" "d5"

$d2
[1] "d2" "d1" "d3" "d4" "d5"

$d3
[1] "d3" "d1" "d2" "d4" "d5"

$d4
[1] "d4" "d1" "d2" "d3" "d5"

$d5
[1] "d5" "d1" "d2" "d3" "d4"
Ben
  • 28,684
  • 5
  • 23
  • 45
1

Using setdiff

t(sapply(x, function(u) c(u, setdiff(x, u))))
   [,1] [,2] [,3] [,4] [,5]
d1 "d1" "d2" "d3" "d4" "d5"
d2 "d2" "d1" "d3" "d4" "d5"
d3 "d3" "d1" "d2" "d4" "d5"
d4 "d4" "d1" "d2" "d3" "d5"
d5 "d5" "d1" "d2" "d3" "d4"

data

x <- c("d1","d2","d3","d4","d5")
akrun
  • 874,273
  • 37
  • 540
  • 662