Reputation: 3195
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.
Upvotes: 0
Views: 74
Reputation: 887251
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"
x <- c("d1","d2","d3","d4","d5")
Upvotes: 1
Reputation: 30474
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"
Upvotes: 1
Reputation: 21982
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"
Upvotes: 1