0
$\begingroup$

Consider that I have a date i.e. 2017-10-23, and want the result to look 23OCT2017

date <- '2017-10-23'

date2 <- toupper(format(as.Date('2017-10-23'),'%d%b%Y'))
str(date2)
chr "23OCT2017"

however this results in character date, however i want that to be numeric but the format should be 23OCT2017. Could any suggest how to accomplish this

$\endgroup$

1 Answer 1

0
$\begingroup$

R doesn't really have the idea of a "format", which I suspect is something you've got from SAS.

What you can do is create a new class, and write a print method for that class to show the values in anyway you like. For example, if I create:

print.d9 = function(x){
    print(
      toupper(
        format(
         as.Date(unclass(x),origin="1970-01-01"),
         '%d%b%Y')))
}

Then a numeric vector looks like numbers:

> v = c(0, 366, 1000)
> v
[1]    0  366 1000

until I re-class it as "d9":

> class(v) = c("numeric","d9")

and then it prints using the print.d9 function:

> v
[1] "01JAN1970" "02JAN1971" "27SEP1972"

But the underlying data are numeric:

> v
[1] "01JAN1970" "02JAN1971" "27SEP1972"
> v+30
[1] "31JAN1970" "01FEB1971" "27OCT1972"

But this is only half the job, for example as is you can't put these into a data frame and still see the character representation:

> data.frame(x1=v)
    x1
1    0
2  366
3 1000

Yeah there's ways round this, but any sensible code would use native R dates as much as possible and only convert to a specific date format at the last moment. R's date objects are numeric and can be put in data frames, unlike my d9 class above. And you've already written code to convert to the format you want.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.