mardi 6 avril 2021

row bind or annotate a dataframe, based on matching using between, on columns

My data looks more or less like this:

dictionary <- data.frame(fruit =  c("apple", "banana", "kiwi"), 
                         min_range = c(1, 520, 1200), 
                         max_range=  c(519, 900, 1800))

data <- data.frame(dictionary_id = c(12,600,1500, 3050, 2))

I would like to annotate the data frame data using the dictionary min and max ranges. using dplyr's between doesn't work, as I would be passing it a column, which it doesn't accept. My approach would be to create an if_else statement inside a mutate(), which would in principle work like this:

data %>%
  mutate(fruit = if_else(dictionary_id >= dictionary$min_range & dictionary_id <= dictionary$max_range,
                          dictionary$fruit,
                          "error"))

Any ideas? Thank you!

Aucun commentaire:

Enregistrer un commentaire