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

______________________________________________
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.

Reply via email to