kosky
kosky

Reputation: 29

Can't use zoo's as.yearmon properly, the transformed column has years showing up like 0086 instead of 1986

Hello and thanks for being here.

I'm trying to convert dates with as.yearmon but the results I'm getting are odd and I do not know how to fix this; I tried searching on here and on the offical package guide without finding someone with the same problem. The problem is that I transformed a column of a dataset which was formatted as "month/year" with as.yearmon but the results were not correct.

For example, the first 3 values of the column of the original DF are: "1/86", "2/86", "3/86".

After using this function to convert them:

library(zoo)
Dates <- Returns
Dates$Month<- zoo::as.yearmon(Dates$Month, "%m / %Y")

[Where "Returns" is the original dataframe and Dates the new one with the modified dates.]

The result I got, instead of being: "gen 1986", "feb 1986", "mar 1986" was "gen 0086", "feb 0086", "mar 0086" and I don know why.

[I should not that "gen", "feb", "mar" are in Italian; I do not know if that matters and I do not know how to change that to "Jan", "Feb", "Mar" which I think I'll have to do as well]

Thanks in advance for your help, if something is not clear just let me know; I'm still a rookie.

Upvotes: 0

Views: 371

Answers (1)

phiver
phiver

Reputation: 23598

You need to use "%m/%y" instead of "%m/%Y". Your dates don't have a the full year notation.

x <- c("1/86", "2/86", "3/86")

zoo::as.yearmon(x, "%m/%y")
[1] "jan 1986" "feb 1986" "mrt 1986"

Date functions return the names in the local locale. If you want them in English:

Sys.setlocale("LC_TIME", "English")

zoo::as.yearmon(x, "%m/%y")
[1] "Jan 1986" "Feb 1986" "Mar 1986"

Everytime you restart R, this will be set back to your locale.

More info here on SO

Upvotes: 1

Related Questions