Home > Enterprise >  How to write a functionin R to swaphalves eg: c(1,2,3,4,5,6) to c(4,5,6,3,2,1)
How to write a functionin R to swaphalves eg: c(1,2,3,4,5,6) to c(4,5,6,3,2,1)

Time:09-19

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

CodePudding user response:

This is simply accomplished using median:

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

swap_fun(1:6)
[1] 4 5 6 3 2 1

CodePudding user response:

We can split() the vector into a list of two, rev()erse the order and then unlist()

my_vector <- 1:6

swap_halves <- function(x) unlist(rev(split(x, sort(rank(x)%%2))))

11 12 13 01 02 03 
 4  5  6  1  2  3 

CodePudding user response:

Updated so vector elements are sorted.

swap_func <-  function(x) { 
  
  names(x) <- seq_len(length(x))
  
  swapped_vec <- c(x[which(names(x) > length(x)/2)], rev(x[which(names(x) <= length(x)/2)]))
  
  return(unname(swapped_vec))  
  
} 


swap_func(x = 3:8)
#> [1] 6 7 8 5 4 3

swap_func(x = 1:6)
#> [1] 4 5 6 3 2 1

Created on 2022-09-19 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related