我有一个数据框,其中有一列字符串需要根据另一个数据框进行分类,该数据框在一列中具有类别标签,而在另一列中具有匹配的术语/模式。
有 50 多个类别,每个字符串可以匹配多个类别,而其他类别则没有匹配项。如何使用类别标签有效地标记这些字符串?
下面是一个简单的示例数据集和我希望得到的输出。如果有什么不同的话,真实数据集中的字符串比这些样本字符串长得多,而且有几十万个。
recipes <- c('fresh asparagus', 'a bunch of bananas', 'one pound pork', 'no fruits, no veggies, no nothing', 'broccoli or spinach','I like apples, asparagus, and pork', 'meats like lamb', 'venison sausage and fried eggs', 'spinach and arugula salad', 'scrambled or poached eggs', 'sourdough english muffins')
recipes_df <- data.frame(recipes, stringsAsFactors = FALSE)
category <- c('vegetable', 'fruit', 'meat','bread','dairy')
items <- c('arugula|asparagus|broccoli|peas|spinach', 'apples|bananas|blueberries|oranges', 'lamb|pork|turkey|venison', 'sourdough', 'buttermilk|butter|cream|eggs')
category_df <- data.frame(category, items)
这是我希望得到的输出:
recipes recipes_category
1 fresh asparagus vegetable
2 a bunch of bananas fruit
3 one pound pork meat
4 no fruits, no veggies, no nothing <NA>
5 broccoli or spinach vegetable
6 I like apples, asparagus, and pork fruit, vegetable, meat
7 meats like lamb meat
8 venison sausage and fried eggs meat, dairy
9 spinach and arugula salad vegetable
10 scrambled or poached eggs dairy
11 sourdough english muffins breads
我相信 grepl 和 for 循环或 apply 版本的某种组合是必要的,但我在下面尝试的示例确实暴露了我对 R 的了解程度。例如使用 sapply 给出了我期望的结果,sapply(category_df$items, grepl, recipes_df$recipes)
但我不确定我如何将这些结果转换为我需要的简单列。
如果我使用此处找到的 categorize 函数,它只会将一个类别与每个字符串匹配:
categorize_food <- function(df, searchString, category) {
df$category <- "OTHER"
for(i in seq_along(searchString)) {
list <- grep(searchString[i], df[,1], ignore.case=TRUE)
if (length(list) > 0) {
df$category[list] <- category[i]
}
}
df
}
recipes_cat <- categorize_food(recipes_df, category_df$items, category_df$category)
同样,此处找到的函数与我正在寻找的函数最接近,但我不明白为什么类别编号会以它们的方式映射。我希望蔬菜类别是 1 而不是 2,乳制品是 5 而不是 3。
vec = category_df$items
recipes_df$category = apply(recipes_df, 1, function(u){
bool = sapply(vec, function(x) grepl(x, u[['recipes']]))
if(any(bool)) vec[bool] else NA
})