[R] Need help on parsing dates

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Mon Feb 23 21:16:30 CET 2004



Ajay Shah wrote:

> I know this:
> 
>   > library(date)
>   > x="1979-04-04"
>   > try=as.date(x, "ymd")
>   > print(try)
>   [1] 4Apr79
> 
> and that `x' here has to be a string, e.g.:
> 
>   > x=1979-04-04
>   > print(x)
>   [1] 1971
> 
> I'm stuck in reading from a file. I say:  
> 
>   > A <- read.table(file="try")
>   > print(A)
>              V1          V2
>   1  1979-04-04 -1.04712042
>   2  1979-04-06  0.54538055
>   3  1979-04-09  0.09663392
>   4  1979-04-11  0.57119871
>   5  1979-04-12  0.73594112
>   6  1979-04-17 -1.54422087
>   7  1979-04-18 -0.20595691
>   8  1979-04-19  0.12700429
>   9  1979-04-20  0.42016807
>   10 1979-04-23 -1.46838241
> 
> I am confused - is V1 a number or a string? Looking at it, it must be
> a string. But yet:
> 
>   > library(date)
>   > try=as.date(A$V1, "ymd")
>   Error in as.date(A$V1, "ymd") : Cannot coerce to date format
> 
> In short, how do I parse in dates of the format yyyy-mm-dd (the ISO
> 8601 format) or the yyyymmdd format.
> 
> And if I may ask the next step: How do I tell R that I have a file
> full of data all of which is time-series data, where V1 is the
> datetime vector, and all the other columns are time-series, to do
> things like ARMA models and ts plots with?
> 

To see what class a column in a data.frame is the best way is to try:

sapply(A, data.class)

My guess is that "V1" is being read in as a factor (default). To convert 
to character to use with as.date, then use

as.date(as.character(A$V1), "ymd")

BTW, I would avoid using "try" as a variable name since "try" is a 
function in the base package.

As for you second question, see the package ts for ARIMA
modeling.

-sundar




More information about the R-help mailing list