admin管理员组

文章数量:1318579

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.

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.

Share Improve this question edited Jan 21 at 13:58 Wiktor Stribiżew 628k41 gold badges498 silver badges611 bronze badges asked Jan 21 at 11:13 JoeJoe 1,3355 silver badges20 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 6

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"

本文标签: rFlip parts of my data which differs in lengthStack Overflow