Reputation: 849
I have two vectors
a <- c(18,19,19,19,21,21,22,23,24,25,26,27,28,30,31,35,36,37)
b <- c(19,25,31,37)
I need the data frame following format:
a b
18 19
19 19
19 19
19 19
21 25
21 25
22 25
23 25
24 25
25 25
26 31
27 31
28 31
30 31
31 31
35 37
36 37
37 37
Here value 19 in vector b
repeat up to the value 19 in vector a
.
After that 21(in a) is the greater than 19 ,so the next value of 25(in b) is be repeat until the 25(in a )
in similar way construct the dataframe.
Thank you.
Upvotes: 2
Views: 220
Reputation: 48191
Alternatively,
data.frame(a, b = sapply(a, function(x) b[x <= b][1]))
# a b
# 1 18 19
# 2 19 19
# 3 19 19
# 4 19 19
# 5 21 25
# 6 21 25
# 7 22 25
# 8 23 25
# 9 24 25
# 10 25 25
# 11 26 31
# 12 27 31
# 13 28 31
# 14 30 31
# 15 31 31
# 16 35 37
# 17 36 37
# 18 37 37
Upvotes: 2
Reputation: 886948
We can get the position index from findInterval
, use that to create the times
for the rep
i1 <- findInterval(b, a)
data.frame(a, b = rep(b, c(i1[1], diff(i1))))
# a b
#1 18 19
#2 19 19
#3 19 19
#4 19 19
#5 21 25
#6 21 25
#7 22 25
#8 23 25
#9 24 25
#10 25 25
#11 26 31
#12 27 31
#13 28 31
#14 30 31
#15 31 31
#16 35 37
#17 36 37
#18 37 37
Upvotes: 4