[R] Changing date format

John McKown john.archie.mckown at gmail.com
Fri Oct 10 14:02:54 CEST 2014


On Fri, Oct 10, 2014 at 1:32 AM, Frederic Ntirenganya <ntfredo at gmail.com> wrote:

Please try to not post in HTML. It is one of the forum "rules".

> Dear All,
>
> The following function gives me what I wanted.
> The input of function is one value and this push me to use sapply function
> to call it.
>
> Is there a better way of doing this?
>
> #====================================================
> day <- function(x){
>
>          if(x== 60) {
>                y = "29 Feb"
>          }
>
>          if(x < 60){
>                 y =  format(strptime(x, format = "%j"), format ="%d-%b")
>         }
>
>         if(x > 60){
>                 y =  format(strptime(x - 1, format = "%j"), format ="%d-%b")
>        }
>     y
> }
>
> sapply(Samaru$Start,day)
>
>  [1] "17-Apr" "27-Apr" "24-Apr" "04-Jun" "25-Apr" "13-May" "22-Apr"
> "05-May" "27-Apr" "13-May" "27-Apr"
> #=======================================================

I make no comment about whether the above is "correct" or you, because
I don't know. There is much that I don't know. There is a way to
reformulate the function in a way that I personally think is better.
You might want to look at:

day <- function(x) { ifelse(x==60,"29
Feb",format(strptime(x-(x>60),format="%j"),format="%d-%b")); }

The "trick" is that x-(x>60) will subtract 1 from x when x is greater
than 60, but 0 if it is less than or equal to 60. And the ifelse takes
care of the case where x is equal to 60. As I said, I don't know that
this really gives you want, but it is functionally equivalent to the
code you posted. However, it is not as obvious. As we say about the
lottery: "You pay your money, you take your chance."


-- 
There is nothing more pleasant than traveling and meeting new people!
Genghis Khan

Maranatha! <><
John McKown



More information about the R-help mailing list