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

后端 未结 1 619
醉酒成梦
醉酒成梦 2021-01-15 05:13

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. Tha

相关标签:
1条回答
  • 2021-01-15 06:12

    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-')
    
    0 讨论(0)
提交回复
热议问题