Convert four digit year values to a date type

后端 未结 4 1914
盖世英雄少女心
盖世英雄少女心 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:14

    Based on the comments it turned out that the person asking the question did not need to change a numeric year to "Date" class; nevertheless, the question asked how to do it so here is an answer.

    Here are a few ways to create a "Date" class object from a 4 digit numeric year. All use as.Date:

    yrs <- c(2001, 2002, 2002, 2002, 2003, 2005)
    

    1) ISOdate

    as.Date(ISOdate(yrs, 1, 1))  # beginning of year
    as.Date(ISOdate(yrs, 12, 31))  # end of year
    

    This ISOdate solution is a bit tricky because it creates an intermediate POSIXct object so time zone problems could exist. You might prefer one of the following.

    2) paste

    as.Date(paste(yrs, 1, 1, sep = "-")) # beginning of year
    as.Date(paste(yrs, 12, 31, sep = "-")) # end of year
    

    3) zoo::as.yearmon

    library(zoo)
    
    as.Date(as.yearmon(yrs)) # beginning of year
    as.Date(as.yearmon(yrs) + 11/12, frac = 1) # end of year
    

    Note: If y is the result for any of the above then format(y, "%Y") gives the character year and as.numeric(format(y, "%Y")) gives the numeric year.

提交回复
热议问题