R: Check if value from dataframe is within range other dataframe

后端 未结 3 962
鱼传尺愫
鱼传尺愫 2021-01-18 05:43

I am looking for a way to look up infromation from 1 dataframe in another dataframe, get a value from that other dataframe and pass it back to the first frame..

exam

3条回答
  •  忘掉有多难
    2021-01-18 06:25

    Since you want to match the columns of id_number and number, you can join x and y on the columns and then mutate the name to NA if the location doesn't fall between from and to, here is a dplyr option:

    library(dplyr)
    y %>% left_join(x, by = c("id_number" = "number")) %>% 
          mutate(name = if_else(location >= from & location <= to, as.character(name), NA_character_)) %>% 
          select(-from, -to) %>% arrange(name) %>% 
          distinct(location, id_number, .keep_all = T)
    
    #   location id_number     name
    # 1      1.5        30 region 1
    # 2      2.8        30 region 2
    # 3      2.0        36 region 7
    # 4     10.0        38     
    # 5      3.5        40     
    

提交回复
热议问题