How to move minus sign from right to left/back to front in R?

1.9k views Asked by At

I've imported the data from a text file and the negative numbers are in the form of 100- (The minus sign in the right side) and I should convert it into -100. Any idea. Thanks in advance.

1

There are 1 answers

3
akrun On BEST ANSWER

We can do this using sub. We capture the numbers as a group ((\\d+)) followed by a - at the end ($) of the string and replace with - followed by the backreference (\\1) of the capture group.

as.numeric(sub("([0-9.]+)-$", "-\\1", v1))
#[1] -100.50 -100.05    0.22  -22.00

data

v1 <- c(-100.5, '100.05-', 0.2200, '22.0-')