Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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

like image 678
dennis Avatar asked Jan 17 '26 10:01

dennis


1 Answers

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)
like image 175
akrun Avatar answered Jan 20 '26 02:01

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!