Convert four digit year values to a date type

后端 未结 4 1920
盖世英雄少女心
盖世英雄少女心 2020-11-29 05:37

I\'ve an integer column in my dataset which has four digit year values, like:

 2001 2002 2002 2002 2003 2005 

I am trying to convert the fo

4条回答
  •  情书的邮戳
    2020-11-29 06:26

    As already recognized by the OP, a year alone does not make up a valid date because month and day are not specified.

    However, some date and date-time conversion functions, e.g., ymd(), parse_date_time(), in the lubridate package recognize a parameter truncated to allow for parsing of incomplete dates:

    yrs <- c(2001, 2002, 2002, 2002, 2003, 2005)
    lubridate::ymd(yrs, truncated = 2L)
    
    [1] "2001-01-01" "2002-01-01" "2002-01-01" "2002-01-01" "2003-01-01" "2005-01-01"
    

    The years have been completed by 1st of January to make a valid date. The result is of class Date.

提交回复
热议问题