【问题标题】:Convert day and month to number of the year (1 - 365) in R将日期和月份转换为 R 中的年数(1 - 365)
【发布时间】:2021-08-18 23:00:08
【问题描述】:

假设我有一个包含两列的数据框,一列代表月,第二列代表天。这是一个简单的例子

month=c(2, 4, ,7, 8, 11, 11, 12)
day=c(21,4,6,8,15,20,30)
monthday=data.frame(month,day)

我想确定一个对应于年份的数字(从 1 到 365)。我该怎么做?

【问题讨论】:

    标签: r date datetime lubridate


    【解决方案1】:

    您可以使用lubridate 包中的yday 函数:

    library(dplyr)
    library(tidyr)
    library(lubridate)
    
    month=c(2, 4,7, 8, 11, 11, 12)
    day=c(21,4,6,8,15,20,30)
    # also define a year so you can parse an actual date
    year = 2021
    monthday=tibble(month,day, year)
    
    monthday %>% 
      # combine into one variable
      tidyr::unite("date", year, month, day, sep = "-", remove = FALSE) %>% 
      # parse as date
      dplyr::mutate(date = lubridate::ymd(date)) %>% 
      # extract day of year
      dplyr::mutate(doy = lubridate::yday(date))
    
    #> # A tibble: 7 x 5
    #>   date       month   day  year   doy
    #>   <date>     <dbl> <dbl> <dbl> <dbl>
    #> 1 2021-02-21     2    21  2021    52
    #> 2 2021-04-04     4     4  2021    94
    #> 3 2021-07-06     7     6  2021   187
    #> 4 2021-08-08     8     8  2021   220
    #> 5 2021-11-15    11    15  2021   319
    #> 6 2021-11-20    11    20  2021   324
    #> 7 2021-12-30    12    30  2021   364
    

    reprex package (v2.0.0) 于 2021 年 5 月 31 日创建

    【讨论】:

      【解决方案2】:

      首先您需要在"POSIXt" 中提供年份和转换。那么我推荐:

      as.numeric(strftime(date, format = "%j"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-24
        • 2014-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-09
        • 1970-01-01
        相关资源
        最近更新 更多