Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205466

How to create a column in r dataframe conditional on other columns

$
0
0

I am trying a create a new column conditional on the present columns. Condition is a matching condition for which I am using grep function.

The data goes like this

            Keyword                         CPC     Impr   Clicks  
    singapore and malaysia tour packages    3.62    241    14     
    +singapore +holiday +packages           3.62    5      0              
    singapore tour packages from bangalore  3.62    201    12     
    "star cruise singapore"                 22.14   31     1    
    [singapore tourism]                     7.30    489    51

So, the first column Keyword has "", [],+ symbols. I want to match these symbols to create a new column with characters like Phrase Match, Exact Match and Broad Match respectively.

I am using grep function for matching the symbols. Please help me with a function to do the create a new column based on the matching condition.

Below are some of the codes that I have written (which ofcourse are throwing errors:( ). Please review them and advise.


pattern<- "[/+]"
pattern1<- "(\\[.*?\\])"
singapore$type<-ifelse(grep('"',singapore$Keyword),as.character("Phrase Match"),
                       ifelse(grep(pattern,singapore$Keyword),as.character("Broad Match"),
                              ifelse(grep(pattern1, singapore$Keyword), as.character("Exact Match"))))

ERROR MESSAGE

Error in `$<-.data.frame`(`*tmp*`, type, value = c("Phrase Match", "Phrase Match",  : 
  replacement has 71 rows, data has 113

func<-function(i)
for(i in 1:length(singapore$Keyword)){
    singapore$type<- i
    if(singapore[grep('"',singapore$Keyword),]){
        i==as.character("Phrase Match")
    }elseif(singapore[grep("[/+]",singapore$keyword),]){
        i==as.character("Broad Match")
    }else(singapore[grep("(\\[.*?\\])", singapore$Keyword),]){
        i==as.character("EXact Match")   
    }
}

ERROR MESSAGE

Error: unexpected symbol in:
"        i==as.character("Phrase Match")
    }elseif">         i==as.character("Broad Match")
Error: object 'i' not found
>     }else(singapore[grep("(\\[.*?\\])", singapore$Keyword),]){
Error: unexpected '}' in "    }">         i==as.character("EXact Match")   
Error: object 'i' not found
>     }
Error: unexpected '}' in "    }"> }
Error: unexpected '}' in "}"


Viewing all articles
Browse latest Browse all 205466

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>