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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-19 10:07:18

问题


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:


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-')


来源:https://stackoverflow.com/questions/41376835/how-to-move-minus-sign-from-right-to-left-back-to-front-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!