I have a column with the values such as this:
Products |
---|
54632 |
54782L |
5847-46x |
7782M |
I want to create a new column with the same values as the original but I want to remove the last character only if its a Letter so the table would look like this
Edited Products |
---|
54632 |
54782 |
5847-46 |
7782 |
Thank you
CodePudding user response:
Use sub
with the regex [A-Z]$
while ignoring case
df$Edited_Products <- sub('[A-Z]$', '', df$Products, ignore.case = TRUE)
df
Products Edited_Products
1 54632 54632
2 54782L 54782
3 5847-46x 5847-46
4 7782M 7782
CodePudding user response:
We could use str_replace_all
with regular expression
`[A-Za-z]$ .... matches letter at the end
library(dplyr)
library(stringr)
df %>%
mutate(Products = str_replace_all(Products, '[A-Za-z]$', ''))
Products
1 54632
2 54782
3 5847-46
4 7782
data:
df <- structure(list(Products = c("54632", "54782L", "5847-46x", "7782M"
)), class = "data.frame", row.names = c(NA, -4L))