[SOLVED] How to write a functionin R to swaphalves eg: c(1,2,3,4,5,6) to c(4,5,6,3,2,1)


This Content is from Stack Overflow. Question asked by RSonowal

I want to write a function to swaphalves a vector of 6 elements,

f2 <- function(x) { if (length(x)<=1) return(x+1) return(x[length(x):1])}

But i want to swap the halves


This is simply accomplished using median:

swap_fun <- function(x) {
   a <- median(x)
   c(x[x>a], rev(x[x<=a]))

[1] 4 5 6 3 2 1

This Question was asked in StackOverflow by user19978016 and Answered by onyambu It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?