I need to categorize the rows of an R dataframe based on a set of category criteria given in another dataframe. The criteria define several categories baed on value ranges of several columns ("traits") in the main dataframe.
Using mtcars as an example dataframe to be categorized, here is the dataframe defining the categories:
criteria <- data.frame(category = c("high", "high", "high", "medium", "medium", "low", "low"),
trait = c("mpg", "cyl", "wt", "mpg", "cyl", "mpg", "cyl"),
min.val = c(20, 6, NA, 20, 4, 15, 6),
max.val = c(NA, 8, 3, NA, 6, 20, 8))
This means, for example, that for a row to be categorized as "high", it needs to have mpg greater than 20, cyl between 6 and 8, and wt less than 3. The output would be identical to the original mtcars dataframe, but with an additional column named "category" that contained values of "high", "medium", "low", and NA for anything that didn't meet any the criteria of any of the categories.
The solution needs to be independent of (1) category name and (2) trait column name so a user can just supply the criteria table with custom category names and any selection of trait columns they wish.
I have a feeling that the solution might involve a complex application of dplyr::filter_at(), but can't figure out how to apply this function to multiple columns, each with a different set of criteria.