假设我有以下数据框和一系列关键字,我正在尝试为每个关键字创建代码。
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
答案 0 :(得分:1)
您可以使用paste()来连接字符串。所以你可以按照
的方式做点什么df[i, 'tags'] <- paste(df[i, 'tags'], "new-tag", sep="|");