This is my vector
my_vec <- letters
Is it possible to put z
letter on 3rd position using slice
(dplyr
) or maybe stringr
?
Its a simple permutation.
CodePudding user response:
You can build a permutation function yourself:
permute <- function(x, i, j) {
x[c(i, j)] <- x[c(j, i)]
x}
permute(letters, 26, 3)
[1] "a" "b" "z" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u"
[22] "v" "w" "x" "y" "c"
CodePudding user response:
We can use indexing in base R
my_vec[c(1:2, length(my_vec), 4:length(my_vec)-1)]
CodePudding user response:
For easier control, you can define some vectors that store the information for your transformation.
target_char <- "z"
target_pos <- 3
my_vec <- letters
append(my_vec[my_vec != target_char], target_char, target_pos - 1)
Which is essentially this:
append(my_vec[my_vec != "z"], "z", 2)
Output
[1] "a" "b" "z" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p"
[18] "q" "r" "s" "t" "u" "v" "w" "x" "y"
CodePudding user response:
You could do
letters %>%
as_tibble() %>%
slice(1:2, 26,3:25) %>%
pull()