Reputation: 27
Im trying to convert a column from character to date.
The current format in the column is "YearMmonth", as in "1990M01". It is a really weird format, so i'm wondering how R reads this when i use the as.Date code. It is basically "Year Month Month-number". I know how to use the rest of the code, i just need to know how to translate this to R.
I have tried using
df <- as.Date(df, "%YM%m", "%Y/%m")
df <- as.Date(paste0("01-", df), format = "%Y/%m/%d")
and alot others, the main problem is translating the character column.
Upvotes: 0
Views: 178
Reputation: 269371
There are several problems with the code in the question:
df
in the question suggests that the result is a data frame yet the result is a Date
class object, not a data frame.Here are some approaches that work.
Use as.yearmon
to convert to a yearmon
object or as.Date(as.yearmon(...))
to convert to a Date object. yearmon
objects directly represent year and month without day so that may be preferable.
library(zoo)
as.yearmon("1990M01", "%YM%m")
## [1] "Jan 1990"
as.Date(as.yearmon("1990M01", "%YM%m"))
## [1] "1990-01-01"
Replacing the M with a minus would also work:
as.yearmon(chartr("M", "-", "1990M01"))
## [1] "Jan 1990"
A way that does not involve any packages is to append a day:
as.Date(paste("1990M01", 1), "%YM%m %d")
## [1] "1990-01-01"
or change the M to a minus and append a minus and a 1 in which case it is already in the default format and no format string is needed.
as.Date(sub("M(\\d+)", "-\\1-1", "1990M01"))
## [1] "1990-01-01"
Upvotes: 2