[R] Convert Factor to Date
Spencer Graves
spencer.graves at effectivedefense.org
Tue Aug 22 20:49:52 CEST 2017
On 2017-08-22 1:30 PM, Patrick Casimir wrote:
> Dear R Fellows,
>
>
> I Have a dataset( data1) with 2 columns of date showing a class of factor. How to convert them to date? Then compare them, keep the greater date only in a new column. Using as.Date to change the class to Date but the data becomes NA.
When I specified a format with the second date, I got the desired
behavior:
> as.Date(factor('1-Nov-16'), '%d-%b-%y')
[1] "2016-11-01"
> as.Date('Nov-16', '%b-%y')
[1] NA
> as.Date(factor('Nov-16'), '%b-%y')
[1] NA
> as.Date('Nov-16', '%b-%y')
[1] NA
To convert the first column, I pasted "1-" in front:
as.Date(paste0('1-', factor('Nov-16')), '%d-%b-%y')
Hope this helps. Spencer
> Much Thanks
>
>
> COL1 COL2
> Apr-16 1-Nov-16
> May-16 1-Nov-16
> Jun-16 1-Nov-16
> Jul-16 1-Nov-16
> Aug-16 1-Nov-16
> Sep-16 1-Nov-16
> Oct-16 1-Nov-16
> Nov-16 1-Nov-16
> Dec-16 1-Nov-16
> Jan-17 1-Nov-16
> Feb-17 1-Nov-16
> Mar-17 1-Nov-16
> Apr-17 1-Nov-16
> May-17 1-Nov-16
> Jun-17 1-Nov-16
> Jul-17 1-Nov-16
> Aug-17 1-Nov-16
> Sep-17 1-Nov-16
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list