Matthew Appleyard
Matthew Appleyard

Reputation: 149

If/else based on the last character

I want to do an if/else on the last character on a string

Data looks like this:

Product:     
ANCHOR AEROSOL CREAM 250G - 2003726   
ARLA B.O.B SKIMMED MILK 2L - 7787579

If it has a L I want to put 1.03 in a column otherwise 1

So far I split the string out and cbind it

extra <- str_split(sains_part$Product, "-", simplify = TRUE)
final <- cbind(sains_part, extra)

But now I don't how to say if data ends in 'L' put 1.03 otherwise 1 and re-combine

Upvotes: 1

Views: 475

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 388982

Instead of splitting the string you can take help of some regex. Get the character before "-" and check if it is "L" or "G" and assign values accordingly.

df$Value <- c(1, 1.03)[(sub(".*(.)\\s+-.*", "\\1", df$Product) == "L") + 1]
df
#                               Product value
#1  ANCHOR AEROSOL CREAM 250G - 2003726  1.00
#2 ARLA B.O.B SKIMMED MILK 2L - 7787579  1.03

data

df <- structure(list(Product = structure(1:2, .Label = c("ANCHOR AEROSOL 
CREAM 250G - 2003726", 
"ARLA B.O.B SKIMMED MILK 2L - 7787579"), class = "factor")), class = 
"data.frame", row.names = c(NA, -2L))

Upvotes: 4

IceCreamToucan
IceCreamToucan

Reputation: 28685

If the two parts of the string are always separated by ' - ' and that character sequence doesn't occur anywhere else, you can avoid using special regex metachracters and instead check whether the string contains 'L - '

df$value <- 1 + grepl('L - ', df$Product)*.03

Upvotes: 2

akrun
akrun

Reputation: 887118

We can use grepl

df$Value <- c(1, 1.03)[grepl("\\b\\d+L\\b", df$Product) + 1]
df$Value
#[1] 1.00 1.03

data

df <- structure(list(Product = c("ANCHOR AEROSOL CREAM 250G - 2003726", 
"ARLA B.O.B SKIMMED MILK 2L - 7787579")), class = "data.frame",
row.names = c(NA, 
-2L))

Upvotes: 3

Related Questions