ATMathew
ATMathew

Reputation: 12856

How to select conditions and assign a new value based on the condition

Let's say I have the following data frame with a series of keywords, and I am trying to create tags for each keyword.

    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"))

I want to generate a new column called tag, which will look as follows.

keyword                 Tag
aaa auto insurance      brand | auto
cheap car insurance     cheap | car
Geico insurance         brand

I've figured out how to create tags in different column, but was wondering how I could add it all in one column with a single delineator ("|").

So here is what I did to generate separate tag columns. I'm wondering how I can alter this code in order to produce what I mentioned previously.

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)

If you're wondering why the tags have 1:7 values, it's because they're unique to a specific tag.

tags = data.frame(id=c(1,2,3,4,5,6,7), tag=c("brand","cheap","affordable","auto","car","quote","rate"))
tags

Upvotes: 0

Views: 701

Answers (1)

timos
timos

Reputation: 2707

You can use paste() to concatenate strings. So you can do something along the lines of

df[i, 'tags'] <- paste(df[i, 'tags'], "new-tag", sep="|");

Upvotes: 1

Related Questions