[R] How to seperate date and time into different columns?

Gabor Grothendieck ggrothendieck at gmail.com
Fri Jan 22 19:43:10 CET 2010


Normally one wants to store time indexes as a single column so its
likely that this is not what you really want to do.  You may wish to
explain what your final objective is and why you want to do this.

However, if you must there are many ways and here is one  The first
two lines load chron and set up some input data.  Now that we have
some input the first line of the solution creates a chron object by
passing to chron the portion prior to the space and the portion after
the space and appending :00 to the latter.  The second line uses
month.day.year to get the date components and subtraction of the date
to get the times.

> library(chron)
> x <- c("4/17/2008 16:01", "4/18/2008 20:01")

> xc <- chron(sub(" .*", "", x), sub(".* (.*)", "\\1:00", x))
> with(month.day.year(xc), data.frame(year, month, day, time = xc - dates(xc)))
  year month day     time
1 2008     4  17 16:01:00
2 2008     4  18 20:01:00

R News 4/1 has an relevant article.

On Fri, Jan 22, 2010 at 1:09 PM, FMH <kagba2006 at yahoo.com> wrote:
> Dear All,
>
> I have a series of data in which the first column consist of a combination of date and time, for instance 17 April 2008 at 4.01pm, such data is recorded as:
>
> 4/17/2008 16:01
>
> I'd like to seperate it into four different columns which consist of Day, Month,Year and Time, respectively.
>
> Could someone please advice me on this mater?
>
> Thank you,
> Fir
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list