[R] Clarification about data/weekday conversion

MacQueen, Don macqueen1 at llnl.gov
Wed Jun 3 17:09:22 CEST 2015


First of all, the as.Date() function converted it to the Date class (not
"Date,format..", and I'd suggest the terminology is important here).

> class('2015-4-1')
[1] "character"

> class( as.Date('2015-4-1') )
[1] "Date"


Second, the format() function always converts to character class.

> n <- 3
> class(n)
[1] "numeric"
> class(format(n))
[1] "character"


or, continuing the date example

> class( format( as.Date('2015-4-1'), '%a %b %d %Y' ) )
[1] "character"



Third, any variable can only be one class at a time (but see caveat
below). It can't be both character and Date class at the same time. So the
answer to your "Is there a way ..." question is no.


Your strategy for dealing with this depends on what you are trying to
accomplish.

For example, if you need to sort by date, then keep the Date class
version. If you want to use the "weekday" version to label things, use the
format() function to create the labels, but keep the Date class version of
the variable, as Jim suggested. If necessary, keep both versions, which I
would do like this (not keeping the original character version):

  Hpc$Date <- as.Date(Hpc$Date, "%d/%m/%Y")

  Hpc$DateC <- format(Hpc$Date, "%a %b %d %Y")


Then use one or the other of them, depending on what is needed.


Caveat: strictly speaking, an object can have more than one class in a
particular narrowly defined way. For example,

> class(Sys.time())
[1] "POSIXct" "POSIXt"


This was the basis of David's suggestion of creating a new class, but I
think that for your purposes at this time, you should stick with the "only
one class at a time" idea.

-- 
Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062





On 6/2/15, 3:31 PM, "t.k. t.k." <tk9830 at gmail.com> wrote:

>Hi everyone
>This is a general question.
>I have imported a "Dates" variable as character. I used the "as.Date"
>command and convert it to Date,format..
>
>I want to change the display of the date to weekday (e.g., I want my time
>series to be instead of 15-04-2010 as Friday-04-2010). I used the "format"
>command but the variable reverts back to character. Is there a way to
>change the day to weekday and my variable remain a "Date,format..."
>variable?
>
>these are the two lines I used as code
>
>Hpc$Date1<- as.Date(Hpc$Date, "%d/%m/%Y")
>
>Hpc$Date1<-format(Hpc$Date1, "%a %b %d %Y")
>
>thanks in advance
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>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