Home > Net >  R Script to rearrange the elements of a vector by interleaving it
R Script to rearrange the elements of a vector by interleaving it

Time:02-05

How to write an R-script to initialize a vector with integers, rearrange the elements by interleaving the first half elements with the second half elements and store in the same vector without using pre-defined function and display the updated vector.

CodePudding user response:

This sounds like a homework question, and it would be nice to see some effort on your own part, but it's pretty straightforward to do this in R.

Suppose your vector looks like this:

vec <- 1:20

vec
#>  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

Then you can just do:

c(t(cbind(vec[1:10], vec[11:20])))
#>  [1]  1 11  2 12  3 13  4 14  5 15  6 16  7 17  8 18  9 19 10 20

This works by joining the two vectors into a 10 x 2 matrix, then transposing that matrix and turning it into a vector.

CodePudding user response:

Or using mapply:

vec <- 1:20

c(mapply(\(x,y) c(x,y), vec[1:10], vec[11:20]))

#>  [1]  1 11  2 12  3 13  4 14  5 15  6 16  7 17  8 18  9 19 10 20
  •  Tags:  
  • Related