Reputation: 61
I have 2 input vectors, iv1
and iv2
, as shown below. I would like to separate the elements of the second vector according to elements of the first. It works like this: The values in iv2
between the first 2 values of iv1
are stored in ov1
, the values in iv2
between the second and third values of iv1
are stored in ov2
, and so on. Note: The values in iv1
and iv2
are already in ascending order. Any thoughts please?
Input:
iv1 <- c(100, 200, 300, 400, 435)
iv2 <- c(60, 120, 140, 160, 180, 230, 250, 255, 265, 270, 295, 340, 355, 401, 422, 424, 430)
Desired output:
ov1 = c(120, 140, 160, 180)
ov2 = c(230, 250, 255, 265, 270, 295)
ov3 = c(340, 355)
ov4 = c(401, 422, 424, 430)
Upvotes: 1
Views: 85
Reputation: 4224
As @RonakShah suggested, the most efficient way in this case may be this:
split(iv2, cut(iv2, breaks = iv1,labels = paste0('ov',1:4)))
Output:
$ov1
[1] 120 140 160 180
$ov2
[1] 230 250 255 265 270 295
$ov3
[1] 340 355
$ov4
[1] 401 422 424 430
Upvotes: 1