I have this character vector
vec <- c("(0,13.2]", "(13.2,28.3]", "(28.3,39.3]", "(39.3,49.4]", "(49.4,59.4]",
"(59.4,69.3]", "(69.3,78.9]", "(78.9,87.8]", "(87.8,95.5]", "(95.5,100]")
and I want to change the entries to
expected <- c("0 to 13.2", "13.2 to 28.3", "28.3 to 39.3", "39.3 to 49.4", "49.4 to 59.4",
"59.4 to 69.3", "69.3 to 78.9", "78.9 to 87.8", "87.8 to 95.5", "95.5 to 100")
What I do is
vec %>%
strsplit(., ",") %>%
lapply(., function(level_i){
from <- gsub("^\\(([0-9])+(\\.)*([0-9])*$", "\\1\\2\\3", level_i[1])
to <- gsub("^([0-9])+(\\.)*([0-9])*]$", "\\1\\2\\3", level_i[2])
paste0(from, " to ", to)
}) %>%
unlist()
# This gives:
# "0 to 3.2" "3.2 to 8.3" "8.3 to 9.3" "9.3 to 9.4" "9.4 to 9.4" "9.4 to 9.3" "9.3 to 8.9"
# "8.9 to 7.8" "7.8 to 5.5" "5.5 to 0"
My codes catches only the last element of a group, i.e. "(0,13.2]" becomes "0 to 3.2" and not "0 to 13.2". How to catch all characters of a group?
>Solution :
With gsub you can capture groups with ():
gsub('\\((.*),(.*)\\]', "\\1 to \\2", vec)
#[1] "0 to 13.2" "13.2 to 28.3" "28.3 to 39.3" "39.3 to 49.4" "49.4 to 59.4"
#[6] "59.4 to 69.3" "69.3 to 78.9" "78.9 to 87.8" "87.8 to 95.5" "95.5 to 100"
To capture exactly the digits instead of .*, you can do. This includes both integers and decimal formats:
gsub('\\((\\d+[\\.]*\\d*),(\\d+[\\.]*\\d*)\\]', "\\1 to \\2", vec)
With all of those backlashes, you can simplify the regex with raw strings: r"{\((\d+[\.]*\d*),(\d+[\.]*\d*)\]}"