Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reorder a vector to first, last, second, second last, etc

Tags:

r

Is there actually an easy solution to reordering a vector like
first element, last element, second element, second last element, etc.

So I expect for c(1,2,3,4,5) to get c(1,5,2,4,3).

The reason is I have a color palette with 16 colours and color 1 is very similar to two but not to color 16. But within my plots, the dots coloured by color 1 are close to the ones are coloured by color 2.

For my color palette I use Set 1 from color brewer and also use colorRampPalette to calculate colours in between, so they get a bit similar.

One solution would be to just sample(my_colors) but actually I would like to reorder them like I told above.

like image 853
drmariod Avatar asked Jan 29 '26 22:01

drmariod


1 Answers

This will do what you need:

a <- c(1,2,3,4,5)
b <- rbind(a,a[5:1])
c <-b [1:5]

Hope this helps

Here is a fiddle

You can generalise this with

rbind(a,rev(a))[1:length(a)] 
like image 115
R. Schifini Avatar answered Jan 31 '26 12:01

R. Schifini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!