Remove year from dates in R

后端 未结 2 1340
广开言路
广开言路 2020-12-10 02:20

I have 20 years worth of weather data, but I\'m only interested in the patterns per year. I don\'t care how June 1995 is different from June 2011, for example. Instead, I wa

相关标签:
2条回答
  • 2020-12-10 02:35

    Does this work?

    temp<-as.Date(c("2014-06-01","1993-06-01", "2013-06-03", "1999-01-31"), "%Y-%m-%d")
    
    x<-format(temp, format="%m-%d")
    
     x
    [1] "06-01" "06-01" "06-03" "01-31"
    
    
    sort(x)
    [1] "01-31" "06-01" "06-01" "06-03"
    
    0 讨论(0)
  • 2020-12-10 02:36

    jalapic's answer just before mine, transforms the date column into a character vector (the object passed in to format is returned as a character for pretty printing).

    according to the OP, one reason for getting rid of the year, perhaps the key one, is to roll-up by by day & month, regardless of year. To me, that suggests a time series is not the right data type for this column, instead you are better off with an ordered factor which will preserve the "sequential properties of dates" as OP requires.

    this is pretty much the

    Granted, a factor does not understand dates or numbers, but it does understand unique values, which in this instance at least, it should behave as the OP wants

    > d = "2014-06-01"
    > d = as.Date(d)
    
    fnx = function(x) {
             unlist(strsplit(as.character(x), '[19|20][0-9]{2}-', fixed=FALSE))[2]
         }
    
    > dm("2012-01-25")
        [1] "01-25"
    
    > dm1 = sapply(column_of_date_objs, fnx)
    
    > new_col = as.factor(dm1, ordered=TRUE)
    
    0 讨论(0)
提交回复
热议问题