On Oct 20, 2014, at 4:32 AM, PIKAL Petr wrote:

> Hi
> 
> Thanks to all who responded.
> 
> My input string is rather clumsy. Actually it can have leading or trailing 
> empty space too, it can be mixture of positive and negative numbers.
> 
> In the meantime I made small function which just strips of - sign and make 
> numbers from factors, find numbers which have - sign and change numbers which 
> shall be negative to negative. Not as elegant as your solution but works even 
> when there are leading or trailing spaces.
> 
> zapor <- function(x) {
> num<-as.numeric(gsub("(-)", "", x))

Might want to just use sub() since your method would accept things like 
"-----100----"

> zap<- grep("-", x)
> num[zap]<- num[zap] * (-1)
> num}
> 
>> x <- as.factor( c("   123.4-   " , "   123   "))
>> zapor(x)
> [1] -123.4  123.0
>> 

gsub("^(\\s+)([0-9.]+)(-){0,1}(\\s)+$", "\\3\\2",
                as.factor( c("   123.4-   " , "   123   ") ) )
[1] "-123.4" "123"  

Then just `as.numeric`. You method looks more elegant. Depending on the local 
you may get into trouble with variation in decimal markers.


> 
> I just thought that there is some reason for presenting negative numbers with 
> minus sign behind the number in finance community and therefore somebody 
> already invented clever way how to deal with such numbers.
> 
> Cheers
> Petr
> 
> 
>> -----Original Message-----
>> From: r-help-boun...@r-project.org [mailto:r-help-bounces@r-
>> project.org] On Behalf Of Marc Girondot
>> Sent: Monday, October 20, 2014 12:53 PM
>> To: r-help@r-project.org
>> Subject: Re: [R] format negative numbers
>> 
>> Is it what you want?
>> 
>>> st <- "0.123-"
>>> gsub("(.+)(-)", "\\2\\1", st)
>> [1] "-0.123"
>>> st <- "0.123"
>>> gsub("(.+)(-)", "\\2\\1", st)
>> [1] "0.123"
>> 
>> Sincerely
>> Marc
>> 
>> Le 20/10/2014 09:03, PIKAL Petr a écrit :
>>> Dear all.
>>> 
>>> Before I start fishing in (for me) murky regular expression waters I
>> try to ask community about changing format of negative numbers.
>>> 
>>> For some reason I get a file with negative numbers formatted with
>> negative sign at end of number.
>>> 
>>> something like
>>> 
>>> 0.123-
>>> 
>>> It is imported as factors and I need to convert it to numbers again.
>> Before converting I need to change it to "correct" format
>>> 
>>> -0.123
>>> 
>>> Does anybody know some simple way?
>>> 
>>> Cheers
>>> Petr
>>> 
>>> 
>>> ________________________________
>>> Tento e-mail a jakékoliv k němu připojené dokumenty jsou důvěrné a
>> 

David Winsemius
Alameda, CA, USA

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to