1 year ago
#358087
Ant
R - Remove first character in a string if it is a comma
I have multiple columns in a dataframe, all of which have some values that may start with a comma. e.g.
ID name email
1 abc , abc@gmail.com
2 , def def@gmail.com, abc@gmail.com
3 ghi ghi@gmail.com
4 ,jkl ,jkl@hotmail.com
I'm trying to find a way to remove the first character of any string in the data frame only if it is a comma and then trim any leading whitespace that results. Any other commas and spaces within the strings will need to remain.
I've tried using the following to get rid of the commas but it doesn't seem to work:
all_df2 <- all_df2 %>%
mutate(across(everything(), gsub, pattern = "\\^,", replacement = ""))
Based on my very limited knowledge of regex, I assumed that \\
was required for special characters, ^
denoted the beginning of a string only and ,
was the character I was wanting to target.
I was planning to trim resulting white space using str_trim
as a separate line of code but if this can be incorporated into the same regex expression, all the better.
r
regex
gsub
stringr
0 Answers
Your Answer