[R] difficulty in Formatting time series data

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Sun Apr 22 19:41:27 CEST 2012


On Sun, 22 Apr 2012, Hasan Diwan wrote:

> Raghu,
>
> On 22 April 2012 09:53, Raghuraman Ramachandran <optionsraghu at gmail.com>wrote:
>
>> I have a data frame (from CSV file) which has its first column called Date.
>> The Date is in the format mm/dd/yyyy. I was trying to get the weekday for
>> these dates and I tried using wday() and day.of.week() functions and both
>> of them gave me precisely the wrong answers. I think the issue lies in the
>> proper formatting of dates. The class of this column is a factor class and
>> hence I tried converting into POSIXlt, xts, zoo objects and yet I could not
>> get the weekday correctly. Anyone has any suggestions please?
>>
>
> Try this:
> # assume dataIn is where the CSV files data is...
> dataIn$Date <- as.POSIXct(dataIn$Date, format='%m/%d/%y')

By far the most common error I see is failing to import the Date column as 
character, instead allowing the import function to convert it to factor, 
after which computations (such as the above suggestion) use the hidden 
factor index instead of the visible character representation, which 
further mystifies beginners.  The conversion above will only work 
correctly if the column was imported as character.  E.g.

dataIn <- read.csv( file="yourdatafile", as.is=TRUE )

OP: Use the str() function to see what types you are working with, and in 
future R-help queries send dput() of the data and code you have tried if 
we are to be able to reproduce your attempts effectively rather than 
reading your mind.

> dataIn <- cbind(dataIn, day.of.week = format(dataIn$Date, format='%A')

Why not just

dataIn$day.of.week <- weekdays( dataIn$Date )

?

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                       Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k



More information about the R-help mailing list