[R] strsplit and regex
ggrothendieck at gmail.com
Thu Oct 16 00:37:55 CEST 2008
Here are several solutions:
# replace first three and last 3 characters with nothing
x <- c("23:10:34", "01:02:03")
gsub("^...|...$", "", x)
# backref = -1 says extract the portion in parens
# it would have returned a list so we use simplify = c
strapply(x, ":(..):", backref = -1, simplify = c)
# convert to POSIXct and use POSIXct's format
# chron times are fractions of a day
# this gives numeric result whereas others give character
floor(24 * 60 * as.numeric(times(x))) %% 60
On Wed, Oct 15, 2008 at 5:54 PM, Redding, Matthew
<Matthew.Redding at dpi.qld.gov.au> wrote:
> Hi All,
> Is there a means to extract the "10" from "23:10:34" in one pass using
> strsplit (or something else)?
> tst <- "23:10:34"
> For example my attempt
>  "" "" "34"
> Obviously it is matching the first two instances of [0-9]. Note that
> there may be only one digit before the first ":".
> How do I anchor the match to the begginning or better still, just
> extract the number I want in one pass?
> I can see that I can add "begin" to the beginning of the string, and
> match that and do something similar at the end, getting rid of empty
> etc - but I think it would take about 3 passess - and the files are
> large. And besides that code would be unlovely.
> Kind regards,
> Matt Redding
> R-help at r-project.org mailing list
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help