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

后端 未结 3 919
鱼传尺愫
鱼传尺愫 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:24

    Another base method (mostly):

    # we need this for the last line - if you don't use magrittr, just wrap the sapply around the lapply
    library(magrittr)
    
    # get a list of vectors where each item is whether an item's location in y is ok in each to/from in x
    locationok  <- lapply(y$location, function(z) z >= x$from & z <= x$to)
    
    # another list of logical vectors indicating whether y's location matches the number in x
    idok  <- lapply(y$id_number, function(z) z== x$number)
    
    # combine the two list and use the combined vectors as an index on x$name
    lapply(1:nrow(y), function(i) {
          x$name[ locationok[[i]] & idok[[i]]  ]
    }) %>% 
    # replace zero length strings with NA values
    sapply( function(x) ifelse(length(x) == 0, NA, x)
    

提交回复
热议问题