[R] Extracting a numeric prefix from a string
(Ted Harding)
Ted.Harding at nessie.mcc.ac.uk
Mon Jan 31 17:09:49 CET 2005
On 31-Jan-05 R user wrote:
> You could use something like
>
> y <- gsub('([0-9]+(.[0-9]+)?)?.*','\\1',x)
> as.numeric(y)
>
> But maybe there's a much nicer way.
>
> Jonne.
I doubt it -- full marks for neat regexp footwork!
To comply fully with Mike's request, I'd wrap it in sort():
sort(as.numeric(y),na.last=TRUE)
[1] 2.40 2.40 3.00 3.00 4.20 5.67 6.00 6.00 NA
or even
unique(sort(as.numeric(y),na.last=TRUE))
[1] 2.40 3.00 4.20 5.67 6.00 NA
Cheers,
Ted.
> On Mon, 2005-01-31 at 08:51 +0000, Mike White wrote:
>> Hi
>> Does anyone know if there is a function similar to as.numeric that
>> will
>> extract a numeric prefix from a string as in the following examples?
>>
>> x<-c(3, "abc", 5.67, "2.4a", "6a", "6b", "2.4.a", 3, "4.2a")
>> df.x<-data.frame(Code=x)
>> x.str<-levels(df.x[,1])
>> # required function result
>> 2.40 3.00 4.20 5.67 6.00 NA
>>
>> Thanks
>> Mike White
>>
>> ______________________________________________
>> R-help at stat.math.ethz.ch mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide!
>> http://www.R-project.org/posting-guide.html
> --
> R user <R-user at zutt.org>
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861 [NB: New number!]
Date: 31-Jan-05 Time: 16:09:49
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list