Reputation: 91
I am currently trying to create sequences between values of different vectors that do not have the same length.
Imagine I have the two following vectors a and b:
a<-c(1, 8, 14, 34, 46, 55)
b<-c(3, 6, 12, 13, 18, 42, 49, 50, 57, 200)
I would like to generate a third vector that shows the sequences between the values of a
and the next highest value of b
(here: 1:3
as 1,2,3
; 8:12
as 8,9,10,11,12
; 14:18
as 14,15,16,17,18
and so on until finally 55:57
as 55,56,57
).
Using mapply
did not yield the desired results.
Upvotes: 2
Views: 560
Reputation: 32558
lapply(a, function(x) x:b[b>x][1])
#[[1]]
#[1] 1 2 3
#[[2]]
#[1] 8 9 10 11 12
#[[3]]
#[1] 14 15 16 17 18
#[[4]]
#[1] 34 35 36 37 38 39 40 41 42
#[[5]]
#[1] 46 47 48 49
#[[6]]
#[1] 55 56 57
Upvotes: 6
Reputation: 887881
We can use findInterval
to subset the 'b' based on the value of 'a' and then with Map
get the corresponding sequence (:=
) between the elements of the 'a' and the subset elements of 'b'
Map(`:`, a, b[findInterval(a, b) + 1])
#[[1]]
#[1] 1 2 3
#[[2]]
#[1] 8 9 10 11 12
#[[3]]
#[1] 14 15 16 17 18
#[[4]]
#[1] 34 35 36 37 38 39 40 41 42
#[[5]]
#[1] 46 47 48 49
#[[6]]
#[1] 55 56 57
Upvotes: 7