In the interest of having a complete answer here, I'm fleshing out @Alex's answer somewhat.
The as.Date
function can be used to convert a character string (or vector thereof) to Date
format. The help page for strptime
(?strptime
) gives some valuable information about possible formats that Date
objects can use.
In your case, you want to convert the NM_DATA$DATE
vector to dates. The format yyyymmdd is represented by %Y%m%d
, thus if your vector is character, we can convert it like so:
NM_DATA$DATE <- as.Date(NM_DATA$DATE, format='%Y%m%d')
However, if it is numeric (instead of character), we first need to coerce to character to avoid an 'origin' must be supplied
error. (You could check the mode of the vector with mode(NM_DATA$DATE)
.)
NM_DATA$DATE <- as.Date(as.character(NM_DATA$DATE), format='%Y%m%d')
Now that the vector is a Date
object, we can format it in various ways (outlined at ?strptime
). To extract year, month and day numbers:
NM_DATA$YEAR <- format(NM_DATA$DATE, '%Y')
NM_DATA$MONTH <- format(NM_DATA$DATE, '%m')
NM_DATA$DAY <- format(NM_DATA$DATE, '%d')
If you want month name, instead, you can use %B
(or %b
, for abbreviated month names), e.g.:
NM_DATA$MONTHNAME <- format(NM_DATA$DATE, '%B')