dennis
dennis

Reputation: 119

move the negative sign from the right side of number to left side in R languge

everyone, In the csv file, if some number is negative, the negative is on right side, such as 56.17-. When importing to R language, I want to move the negative sign from right ride to left side to become a negative number, such as -56.17. However, if the number is negative number such as -56.17 or positive number 56.17, the number remains as negative or positive.Thank you so much.Dennis

Upvotes: 2

Views: 333

Answers (1)

akrun
akrun

Reputation: 887078

We can do this with sub to capture all the characters ((.*)) from the start (^) and match the - at the end ($) of the string, replace it with the - and the backreference (\\1) of the captured group

as.numeric(sub("^(.*)-$", "-\\1", v1))
#[1] -56.17 -56.17  56.17

data

v1 <- c('56.17-', -56.17, 56.17)

Upvotes: 4

Related Questions