Izzy
Izzy

Reputation: 41

Create a column based on a substring in R

I want to create a column in a data frame having values "Mobile" and "Desktop" based on Campaign Name in another column, how should I got about doing this ?

For example :

Campaign                         Device 
Branded-Desktop-Campaign1        Desktop
Branded-Mobile-Campaign2         Mobile

My data frame has around 2000 rows.

Upvotes: 2

Views: 122

Answers (3)

MarkusN
MarkusN

Reputation: 3223

You can use regex to look for keywords in your Campaing String and use the result to build your "Device" column:

library(dplyr)
df %>%
    mutate(mobile = grepl("Mobile", Campaign),
           desktop = grepl("Desktop", Campaign),
           Device = ifelse(mobile, "Mobile", "Desktop"))

Of course you can put the regex directly into the ifelse function to do it one step.

Upvotes: 0

akrun
akrun

Reputation: 887831

We can use sub. We match the pattern one or more characters followed by - (.*-), then capture one or more characters that are not a - ([^-]+) as a group. In the replacement, we use the backreference.

sub('.*-([^-]+)-.*', '\\1', df1$Campaign)
#[1] "Desktop" "Mobile" 

Or we can use stri_extract_first from stringi

library(stringi)
stri_extract_first_regex(df1$Campaign, '(?<=\\-)\\w+')
#[1] "Desktop" "Mobile" 

Upvotes: 2

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193677

Assuming you're dealing with something like:

x <- c("Branded-Desktop-Campaign1", "Branded-Mobile-Campaign2")

Try:

gsub(".*-(.*)-.*", "\\1", x)
## [1] "Desktop" "Mobile" 

Upvotes: 3

Related Questions