将日和月转换为 R 中的年数 (1 - 365)

Convert day and month to number of the year (1 - 365) in R

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

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)与年中的某一天相对应。我该怎么做?

首先您需要提供年份并在 "POSIXt" 中转换所有内容。那我推荐:

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

您可以使用 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-05-31