How can I add a value inside a string when a condition is met.
For example, take the following data:
my_data <- c("ab 93 1455 1863 2713 sb 673 771 1601 1969",
"ab 93 1098 1455 2423 2427 sb 168 673 1256",
"ab 93 1098; sb 1256")
I want to add a ";" when a number proceeds a character.
Therefore, I would like the output to be:
output<- c("ab 93 1455 1863 2713; sb 673 771 1601 1969",
"ab 93 1098 1455 2423 2427; sb 168 673 1256",
"ab 93 1098; sb 1256")
If this solution could be completed in the context of a data frame that would be great.
So far, I have been able to detect the condition I'm interested in using the following code:
str_detect(my_data, "[0-9] [a-z]")
[1] TRUE TRUE FALSE
But I am having trouble moving beyond this point.
Thank you for the help!
CodePudding user response:
Of course, use regular expressions:
output <- gsub("(\\d)( [a-zA-Z])", "\\1;\\2", my_data)
print(output)
# [1] "ab 93 1455 1863 2713; sb 673 771 1601 1969" "ab 93 1098 1455 2423 2427; sb 168 673 1256"
# [3] "ab 93 1098; sb 1256"