The string I have is separated by dash with positive and negative numbers. For example, two strings that I have look like:
"1-2--3"
"-1-2--3"
and I want to extract "1", "2", "-3" from string 1
and to have "-1", "2", "-3" from string 2
How can I do it in R?
You can use stringr
for easy splitting with a positive look behind
library(stringr)
x <- c("1-2--3", "-1-2--3")
str_split(x, "(?<=\\d)-")
# [[1]]
# [1] "1" "2" "-3"
#
# [[2]]
# [1] "-1" "2" "-3"
This splits the string at each dash that follows a number.
As pointed out by @IceCreamToucan, this would work fine with the base R strsplit
function as well if you set perl=TRUE
strsplit(x, "(?<=\\d)-", perl=TRUE)
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