0

I'm trying to assign the value from one column in one data-frame to another data-frame if variable x is within the values of variables y and z.

Here's a working example

df <- data.frame("sound" = c("a", "b", "c", "d", "e", "f", "g"), 
                 "start_time" = c(1.2, 1.8, 3.75, 4, 4.4, 5.7, 7), 
                 "end_time" = c(1.4, 1.9, 4, 4.2, 4.5, 6.9, 8))

num_df <- data.frame("UniqueNumb" = c(1, 2, 3, 4),
                    "start_time" = c(1, 3.5, 5, 10),
                    "end_time" = c(2, 4.5, 8.5, 13))

In these examples, what I want to do is assign the UniqueNumb from num_df to each row in df if the start_time and end_time of each sound falls within the start_time and end_time of each UniqueNumb in num_df.

So the resulting df should look like this:

  sound start_time end_time  UniqueNumb
1     a       1.20      1.4  1
2     b       1.80      1.9  1
3     c       3.75      4.0  2
4     d       4.00      4.2  2
5     e       4.40      4.5  2
6     f       5.70      6.9  3
7     g       7.00      8.0  3

Any tips?

user9974638
  • 171
  • 8
  • I think this will help you get started https://stackoverflow.com/questions/24480031/overlap-join-with-start-and-end-positions – Ronak Shah Mar 31 '21 at 10:17

1 Answers1

0
library(fuzzyjoin)
fuzzy_left_join(df, num_df, by = c("start_time" = "start_time", "end_time" = "end_time"), match_fun = c(`>=`, `<=`))

  sound start_time.x end_time.x UniqueNumb start_time.y end_time.y
1     a         1.20        1.4          1          1.0        2.0
2     b         1.80        1.9          1          1.0        2.0
3     c         3.75        4.0          2          3.5        4.5
4     d         4.00        4.2          2          3.5        4.5
5     e         4.40        4.5          2          3.5        4.5
6     f         5.70        6.9          3          5.0        8.5
7     g         7.00        8.0          3          5.0        8.5
AnilGoyal
  • 25,297
  • 4
  • 27
  • 45