0

一連のキーワードを含む次のデータフレームがあり、キーワードごとにタグを作成しようとしているとします。

    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

別の列にタグを作成する方法を理解しましたが、単一のデリニエーター( "|")を使用してすべてを1つの列に追加するにはどうすればよいか疑問に思いました。

これが、個別のタグ列を生成するために私が行ったことです。前に述べたものを生成するために、このコードをどのように変更できるのか疑問に思っています。

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
4

1 に答える 1

1

past()を使用して文字列を連結できます。だからあなたはの線に沿って何かをすることができます

df[i, 'tags'] <- paste(df[i, 'tags'], "new-tag", sep="|");
于 2012-07-19T15:59:04.130 に答える