[R] Extracting numeric part from a string

Marc Schwartz marc_schwartz at me.com
Thu Aug 3 02:45:04 CEST 2017


> On Aug 2, 2017, at 7:42 PM, Marc Schwartz <marc_schwartz at me.com> wrote:
> 
> 
>> On Aug 2, 2017, at 6:59 PM, Christofer Bogaso <bogaso.christofer at gmail.com> wrote:
>> 
>> Hi again,
>> 
>> I am struggling to extract the number part from below string :
>> 
>> "\"cm_ffm\":\"563.77\""
>> 
>> Basically, I need to extract 563.77 from above. The underlying number
>> can be a whole number, and there could be comma separator as well.
>> 
>> So far I tried below :
>> 
>>> library(stringr)
>> 
>>> str_extract("\"cm_ffm\":\"563.77\"", "[[:digit:]]+")
>> 
>> [1] "563"
>> 
>>> 
>> 
>> However, above code is only extracting the integer part.
>> 
>> Could you please help how to achieve that. Thanks,
> 
> 
> Using ?gsub:
> 
> X <- "\"cm_ffm\":\"563.77\""
> 
> > gsub("[^0-9.]", "",  X)
> [1] "563.77"
> 
> or
> 
> > gsub("[^[:digit:].]", "",  X)
> [1] "563.77"
> 
> 
> Basically, remove any characters that are not digits or the decimal point, presuming your pattern is consistent across your data.


Sorry, forgot that you indicated that there could be a comma:

X <- "\"cm_ffm\":\"1,563.77\""

> gsub("[^0-9.,]", "",  X)
[1] "1,563.77"

> gsub("[^[:digit:].,]", "",  X)
[1] "1,563.77"


Regards,

Marc



More information about the R-help mailing list