rstringgsub

Flip parts of my data which differs in length


I am trying to flip my data each time we see a -, this is probably best explained in an example;

myDat
"11-11 10-30" "1-1 30-29" "9-8" "1-1 1-1 1-3" "0-1 7-12" "5-8 20-45"

When I flip this on - I am trying to get;

myDat
"11-11 30-10" "1-1 29-30" "8-9" "1-1 1-1 3-1" "1-0 12-7" "8-5 45-20"

My initial thought was to do this using a gsub or sub and just flip the number each time we see a - but this was tricky as I have differing lengths, maybe a better was to do it is using strsplit(), splitting on the - and pasting back together, although I'm not too familiar with that function.


Solution

  • You can try gsub like below

    > gsub("(\\d+)-(\\d+)", "\\2-\\1", myDat)
    [1] "11-11 30-10" "1-1 29-30"   "8-9"         "1-1 1-1 3-1" "1-0 12-7"   
    [6] "8-5 45-20"
    

    If you are interested in the strsplit-based solution, probably you can take a look at this (although it is much less simple or efficient than gsub)

    sapply(
      strsplit(myDat, " "),
      \(s) {
        paste0(sapply(
          strsplit(s, "-"),
          \(x) {
            paste0(rev(x), collapse = "-")
          }
        ), collapse = " ")
      }
    )
    

    and it also gives the same output as desired

    [1] "11-11 30-10" "1-1 29-30"   "8-9"         "1-1 1-1 3-1" "1-0 12-7"   
    [6] "8-5 45-20"