简体   繁体   中英

How to write a function to create a vector x of length l, swap x[1:1/L] elements with x[1+1/L:L]

I have to create a vector x of length l that swaps the x[1:1/l] elements with the x[1+1/l:l]. If the length of the vector is odd the middle element is unchanged.

Output should be c(A,B,C,D,E,F) to c(D,E,F,A,B,C) if the length of the vector is even. If the length of the vector is odd, for c(A,B,C,D,E) it should be c(D,E,C,A,B).

Any hints to do this? Is there any other way?

Something like this perhaps.

f <- \(x) {
  n <- length(x)
  n2 <- n/2
  if (n %in% 0:1) x
  else if (n %% 2 != 0) {
    fl <- floor(n2)
    cl <- ceiling(n2)
    c(x[(cl + 1):n], x[cl], x[1:fl])
  } else {
    c(x[(n2 + 1):n], x[1:n2])
  }
}


f(LETTERS[1:6])
# [1] "D" "E" "F" "A" "B" "C"

f(LETTERS[1:5])
# [1] "D" "E" "C" "A" "B"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM