-1

Reproducible Example

df <- data.frame("col1" = 1:3, "col2" = c(0.9, '9-', 10))

  col1 col2
1    1  0.9
2    2   9-
3    3   10

Expected output

  col1 col2
1    1  0.9
2    2   -9
3    3   10

Question

I"m trying to replace all the - in a column and paste it in the front instead. Could anyone show me how to do this? Thank you!

Javier
  • 730
  • 4
  • 17

1 Answers1

1

We can use sub to capture the characters before the - as one group and the - as second group, in the replacement provide the backreference of the capture groups

sub("(.*)(-)$", "\\2\\1", df$col2)
#[1] "0.9" "-9"  "10" 

Or using one capture group

sub("(.*)-$", "-\\1", df$col2)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thanks Akrun. Could u explain how do i read \\2\\1 ? – Javier Jun 25 '19 at 06:25
  • 1
    @Javier If you check `(.*)`, it is the block of characters that is captured as a group. It is the first capture group, the second one is `(-)`). In the replcement, we switch the backreference of the second first (`\\2`) and then the first so as to rearrange the substring within the string – akrun Jun 25 '19 at 06:26