[英]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)。 我怎样才能做到这一点?
您可以使用来自yday
package 的lubridate
function:
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
由代表 package (v2.0.0) 于 2021 年 5 月 31 日创建
首先,您需要在"POSIXt"
中提供年份并转换所有内容。 那我推荐:
as.numeric(strftime(date, format = "%j"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.