Thanks for the help and the various options! Putting the + outside the brackets
worked, but I like the strsplit option. Always nice to learn new functions!
Aloha,
Tim
--- On Thu, 5/21/09, Marc Schwartz <marc_schwartz at me.com> wrote:
> From: Marc Schwartz <marc_schwartz at me.com>
> Subject: Re: [R] help with gsub and date pattern
> To: "Tim Clark" <mudiver1200 at yahoo.com>
> Cc: r-help at r-project.org
> Date: Thursday, May 21, 2009, 11:34 AM
> On May 21, 2009, at 4:13 PM, Tim
> Clark wrote:
>
> >
> > Dear List,
> >
> > I am having a problem using gsub to remove dates from
> a date/time string.
> >
> > For example:
> >
> > x<-c("5/31/2009 12:34:00","6/1/2009 1:14:00")
> >
> > I would like to remove the date and have just the
> time.
> >
> > I have tried:
> > gsub("[0-9+]/[0-9+]/[0-9+]","",x)
> >
> > and various versions.? I think my problem is that
> the / is a special character and is telling it something
> that I don't mean.? I would appreciate any suggestions
> on how to proceed.
> >
> > Thanks,
> >
> > Tim
>
>
>
> Switch the '+' to outside the brackets:
>
> > gsub("[0-9]+/[0-9]+/[0-9]+ ","",x)
> [1] "12:34:00" "1:14:00"
>
>
> A few other options:
>
> # Use strsplit
> > sapply(strsplit(x, split = " "), "[", 2)
> [1] "12:34:00" "1:14:00"
>
>
> # Return the pattern contained within the parens
> # See ?regex
> > gsub("^.* (.*)$", "\\1", x)
> [1] "12:34:00" "1:14:00"
>
>
> # Replace the characters up to the space with an empty
> vector
> > gsub("^.* ", "", x)
> [1] "12:34:00" "1:14:00"
>
>
> HTH,
>
> Marc Schwartz
>
>