I have a dataframe in r with a column which is a big string. I want to use that string to create a new column with specific values.
This is the sample dataframe:
dom <- data.frame(
Site = c("alpha", "beta", "charlie", "delta"),
Banner = c("testing_Watermelon -DPI_300x250 v2" , "notest_Vanilla Latte-DPI_300x250 v2" , "bottle :15s","aaaa vvvv cccc Build_Mobile_320x480")
)
Now if the column Banner has string containing Watermelon or Vanilla then the new column label should have values only Watermelon or Vanilla else Default. Below is what the expected dataframe should be like.
How can I use grep or anything else to have multiple conditions in that?
dom_output <- data.frame(
Site = c("alpha", "beta", "charlie", "delta"),
Banner = c("testing_Watermelon -bbb_300x250 v2" , "notest_Orange aaa_300x250 v2" , "bottle :15s","aaaa vvvv cccc 320x480"),
label = c("Watermelon","Vanilla","Default","Default")
)
library(stringr)
dom$label = str_extract(dom$Banner, "Watermelon|Vanilla")
dom$label[is.na(dom$label)] <- "Default"
dom
# Site Banner label
# 1 alpha testing_Watermelon -DPI_300x250 v2 Watermelon
# 2 beta notest_Vanilla Latte-DPI_300x250 v2 Vanilla
# 3 charlie bottle :15s Default
# 4 delta aaaa vvvv cccc Build_Mobile_320x480 Default
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With