Home > Mobile >  Roll vector so max value is centered and order of values relative to it stay the same
Roll vector so max value is centered and order of values relative to it stay the same

Time:02-13

How can I roll a vector so the max value is in the middle and the order of values relative to it stay the same?

If the length of the vector is even, then just put it in the mean value: n/2

If I have: vec <- c(0, 2, 4, 3, 1, 8)

I want to return: 3 1 8 0 2 4

Thanks.

CodePudding user response:

You can use the SOfun package which has a function called shifter:

library(SOfun)

shifter(vec, which.max(vec) - length(vec) / 2)

Output

[1] 3 1 8 0 2 4

In the second case, you have:

vec <- c(0, 8, 4, 3, 1, 2)

with max value before the middle, resulting in a negative shift:

shifter(vec, which.max(vec) - length(vec) / 2)

Output

[1] 2 0 8 4 3 1
  •  Tags:  
  • r
  • Related