mercredi 3 juin 2020

Lookup (or merge) 2 dataframes using multiple conditions [duplicate]

I’m learning r and having a hard time getting over a hurdle to do something that seems like it should be simple to do. I’ve tried using mutate, and multiple ways of configuring if statements.

I have a df1 which I want to compare with a “lookup” table. I want to compare every value in df1 with df2$start2 and df2$end2. If df1$start1 is >= to df2$start & <= df2$end2, I want to insert the corresponding df2$id value into df1. I'm not feeling picky about an approach to make this work. I can solve this in Excel, but having a problem thinking about how to get this to work in R. Thank you.

df1 <- data.frame(
start1 = c(3,4,11,12,18, 20, 21, 24, 31, 35, 42)

)

df2 <- data.frame(
id = c("z_1","z_2", "z_3", "z_4", "z_5", "z_6"),
start2 = c (0, 5, 15, 20, 30, 40 ),
end 2= c(4, 15, 19, 29, 39, 45)

)

expected_result<- data.frame(
start1 = c(3,4, 11, 12, 18, 20, 21, 24, 31, 35, 42),
id1 = c("z_1", "z_1", "0", "0", "z_3", "z_4", "z_4", "z_4", "z_5", "z_5", "z_6"))

Aucun commentaire:

Enregistrer un commentaire