简体   繁体   English

R:将月份分配给一年中的某天

[英]R: assign months to day of the year

Here's my data which has 10 years in one column and 365 day of another year in second column 这是我的数据,其中一列包含10年,第二列包含另一年365天

dat <- data.frame(year = rep(1980:1989, each = 365), doy= rep(1:365, times = 10))

I am assuming all years are non-leap years ie they have 365 days. 我假设所有年份都是非-年,即它们有365天。

I want to create another column month which is basically month of the year the day belongs to. 我想创建另一个列month ,基本上是该日期所属的月份。

library(dplyr)

dat %>% 
   mutate(month = as.integer(ceiling(day/31)))

However, this solution is wrong since it assigns wrong months to days. 但是,此解决方案是错误的,因为它将错误的月份分配给了几天。 I am looking for a dplyr solution possibly. 我可能正在寻找dplyr解决方案。

We can convert it to to datetime class by using the appropriate format (ie %Y %j ) and then extract the month with format 我们可以使用适当的format (即%Y %j )将其转换为datetime类,然后使用format提取month

dat$month <- with(dat, format(strptime(paste(year, doy), format = "%Y %j"), '%m'))

Or use $mon to extract the month and add 1 或者使用$mon提取月份并加1

dat$month <- with(dat, strptime(paste(year, doy), format = "%Y %j")$mon + 1)
tail(dat$month)
#[1] 12 12 12 12 12 12

This should give you an integer value for the months: 这应该为您提供月份的整数值:

dat$month.num <- month(as.Date(paste(dat$year, dat$doy), '%Y %j'))

If you want the month names: 如果您想要月份名称:

dat$month.names <- month.name[month(as.Date(paste(dat$year, dat$doy), '%Y %j'))]

The result (only showing a few rows): 结果(仅显示几行):

> dat[29:33,]
   year doy month.num month.names
29 1980  29         1     January
30 1980  30         1     January
31 1980  31         1     January
32 1980  32         2    February
33 1980  33         2    February

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM