How to read data files containing time data by R?

For example, the data file test.dat is:

4188418000628;       1  ;    05-19-2002  ;    06-23-2002  ;     26.6;   3.71;   3.03;  0
4188418000628;       1  ;    05-19-2002  ;    07-15-2002  ;     28.1;   3.41;   2.79;  0
4188418000628;       1  ;    05-19-2002  ;    08-15-2002  ;     32.0;   3.43;   3.30;  0

The field is separated by ";" and the third and fourth columns are time data.

 

  1. Read time data as characters.

    y<-read.table("test.dat", sep=";", as.is=T, strip.white=T)
    

    and we can get

    > y$V3
    [1] "05-19-2002" "05-19-2002" "05-19-2002"
    

    The argument strip.white is used only when sep has been specified, and allows the stripping of leading and trailing white space from `character' fields (`numeric' fields are always stripped). If strip.white=F, then we will get

    > y1<-read.table("test.dat", sep=";", as.is=T)
    > y1$V3
    [1] "    05-19-2002  " "    05-19-2002  " "    05-19-2002  "
    

    The default behavior of read.table is to convert character variables (which are not converted to logical, numeric or complex) to factors. When as.is=T, read.table will not convert character variables to factors.

     

  2. Convert characters to a Julian date by using the function as.date in library(survival)

    library(survival)
    > a<-as.date(y$V3)
    > a
    [1] 19May2002 19May2002 19May2002
    > b
    [1] 23Jun2002 15Jul2002 15Aug2002
    > a[1]-b[1]
    [1] -35
FAQ Category