New column from non-standard date factor in R

后端 未结 1 762
栀梦
栀梦 2020-12-12 02:55

I have a dataframe with an oddly formatted dates column. I\'d like to create a column just showing the year from the original date column and I am having trouble coming up w

相关标签:
1条回答
  • This should work:

    transform(toy,Year=format(strptime(date,"%m-%d-%y"),"%Y"))
    

    This produces

    ##   org country     date Year
    ## 1   a       1 01-09-14 2014
    ## 2   b       2 01-10-07 2007
    ## 3   c       3 11-31-99 <NA>
    ## 4   d       4 10-31-12 2012
    

    I initially thought that the NA value was because the %y format indicator wasn't smart enough to handle previous-century dates, but ?strptime says:

    ‘%y’ Year without century (00-99). On input, values 00 to 68 are prefixed by 20 and 69 to 99 by 19 - that is the behaviour specified by the 2004 and 2008 POSIX standards, but they do also say ‘it is expected that in a future version the default century inferred from a 2-digit year will change’.

    implying that it should be able to handle it.

    The problem is actually that 31 November doesn't exist ...

    (You can drop the date column at your leisure ...)

    0 讨论(0)
提交回复
热议问题