假设我有以下包含一系列关键字的数据框,并且我正在尝试为每个关键字创建标签。
keywords = data.frame(keyword=c("aaa auto insurance","cheap car insurance",
"affordable auto insurance","fast insurance quotes","cheap insurance rates",
"Geico insurance","State Farm insurance quote"))
我想生成一个名为 tag 的新列,如下所示。
keyword Tag
aaa auto insurance brand | auto
cheap car insurance cheap | car
Geico insurance brand
我已经想出了如何在不同的列中创建标签,但想知道如何使用单个轮廓符(“|”)将所有标签添加到一个列中。
所以这就是我为生成单独的标签列所做的事情。我想知道如何更改此代码以生成我之前提到的内容。
main <- function(df) {
brand <- c("aaa","State Farm","Geico","Progressive")
cheap = c("cheap","cheapest")
affordable=c("affordable")
auto=c("auto")
car=c("car")
quote=c("quote","quotes")
rate=c("rate","rates")
for(i in 1:nrow(df)) {
words = strsplit(as.character(df[i, 'keyword']), " ")[[1]]
if(any(brand %in% words)){
df[i, 'brand'] <- 1 }
else{
df[i, 'brand'] <- "NULL" }
if(any(cheap %in% words)){
df[i, 'cheap'] <- 2 }
else{
df[i, 'cheap'] <- "NULL" }
if(any(affordable %in% words)){
df[i, 'affordable'] <- 3 }
else{
df[i, 'affordable'] <- "NULL" }
if(any(auto %in% words)){
df[i, 'auto'] <- 4 }
else{
df[i, 'auto'] <- "NULL" }
if(any(car %in% words)){
df[i, 'car'] <- 5 }
else{
df[i, 'car'] <- "NULL" }
if(any(quote %in% words)){
df[i, 'quote'] <- 6 }
else{
df[i, 'quote'] <- "NULL" }
if(any(rate %in% words)){
df[i, 'rate'] <- 7 }
else{
df[i, 'rate'] <- "NULL" }
}
return(df)
}
main(keywords)
如果您想知道为什么标签具有 1:7 的值,那是因为它们对于特定标签是唯一的。
tags = data.frame(id=c(1,2,3,4,5,6,7), tag=c("brand","cheap","affordable","auto","car","quote","rate"))
tags