2

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?

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
LulY
  • 976
  • 1
  • 9
  • 24

3 Answers3

3

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*)\]}"

Maël
  • 45,206
  • 3
  • 29
  • 67
2

You can try the trick read.table + trimws

do.call(paste, c(
    read.table(text = trimws(vec, whitespace = "[\\(\\]]"), sep = ","),
    sep = " to "
))

which gives

 [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"

Another trick is sub + trimws + chartr

> sub(",", " to ", trimws(chartr("(]", "  ", 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"
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
2

We could use gsub twice:

gsub("[^a-zA-Z0-9. ]", "", gsub(",", " to ", 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" 
TarJae
  • 72,363
  • 6
  • 19
  • 66