[R] Date from text

Enrico Schumann e@ @end|ng |rom enr|co@chum@nn@net
Fri May 15 13:57:22 CEST 2020


On Fri, 15 May 2020, Poizot Emmanuel writes:

> Dear all,
>
> I've a data frame with a column "Date":
>
> [1] 11-1993 11-1993 11-1993 11-1993 11-1993 11-1993 11-1996 11-1996 11-1996
> [10] 11-1996 11-1996 11-1996 02-1998 02-1998 02-1998 02-1998 02-1998 02-1998
> [19] 11-1998 11-1998 11-1998 11-1998 11-1998 11-1998 10-2001 10-2001 10-2001
> [28] 10-2001 10-2001 10-2001 02-2003 02-2003 02-2003 02-2003 02-2003 02-2003
> [37] 11-2004 11-2004 11-2004 11-2004 11-2004 11-2004 11-2005 11-2005 11-2005
> [46] 11-2005 11-2005 11-2005 11-2007 11-2007 11-2007 11-2007 11-2007 11-2007
> [55] 10-2008 10-2008 10-2008 10-2008 10-2008 10-2008 03-2009 03-2009 03-2009
> [64] 03-2009 03-2009 03-2009 10-2012 10-2012 10-2012 10-2012 10-2012 10-2012
> [73] 12-2017 12-2017 12-2017 12-2017 12-2017 12-2017 12-2018 12-2018 12-2018
> [82] 12-2018 12-2018 12-2018
>
> I want to convert that into real dates:
> as.POSIXct(Date, format="%m-%Y") always return "NA" values.
> Where am I wrong ?
>
> regards

If you really want a date, I'd suggest 'as.Date'. The help
for ?as.Date says:

  "If the date string does not specify the date completely,
   the returned answer may be system-specific."

So perhaps try something like

    as.Date(paste0("01-", "11-1993"), format = "%d-%m-%Y")
    ## [1] "1993-11-01"

Or look at 'yearmon' in package 'zoo':

    library("zoo")
    as.yearmon("11-1993", format = "%m-%Y")
    ## [1] "Nov 1993"

-- 
Enrico Schumann
Lucerne, Switzerland
http://enricoschumann.net



More information about the R-help mailing list