Jörg Groß
2009-Jan-17 04:00 UTC
[R] splitting a string / finding a numeric value within a string
Hi,
I have this variable;
x <- c("test_01.log")
and I want to extract the number (01) out of the variable.
So that I get;
> x
[1] 1
I tried strsplit, but I don't know how to refer to the result.
Can someone help me with that?
[[alternative HTML version deleted]]
Jorge Ivan Velez
2009-Jan-17 04:30 UTC
[R] splitting a string / finding a numeric value within a string
Dear Jörg, Try this:> gsub("^.*['_']|[.].*$", "", "test_01.log")[1] "01"> as.numeric(gsub("^.*['_']|[.].*$", "", "test_01.log"))[1] 1 HTH, Jorge On Fri, Jan 16, 2009 at 11:00 PM, Jörg Groß <joerg@licht-malerei.de> wrote:> Hi, > > I have this variable; > > > x <- c("test_01.log") > > > and I want to extract the number (01) out of the variable. > So that I get; > > > x > [1] 1 > > > > I tried strsplit, but I don't know how to refer to the result. > > Can someone help me with that? > [[alternative HTML version deleted]] > > ______________________________________________ > 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. >[[alternative HTML version deleted]]
Gabor Grothendieck
2009-Jan-17 04:39 UTC
[R] splitting a string / finding a numeric value within a string
The first one replaces non-numerics with the empty string
and the second one returns numerics directly:
gsub("[^0-9]", "", "test_01.log")
# or
library(gsubfn)
strapply("test_01.log", "[0-9]+")[[1]]
On Fri, Jan 16, 2009 at 11:00 PM, J?rg Gro? <joerg at licht-malerei.de>
wrote:> Hi,
>
> I have this variable;
>
>
> x <- c("test_01.log")
>
>
> and I want to extract the number (01) out of the variable.
> So that I get;
>
> > x
> [1] 1
>
>
>
> I tried strsplit, but I don't know how to refer to the result.
>
> Can someone help me with that?
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.
>