简体   繁体   English

使用lubridate将单独的'year'和'day'列转换为一个'date'列?

[英]Convert separate 'year' and 'day' columns into one 'date' column with lubridate?

I have one column for 'year' and one column for 'day' (julian day) and I want to use these columns to make a 'date' (2002-12-03 or any format is okay). 我有一个列为'year',一列为'day'(julian day),我想使用这些列来制作'date'(2002-12-03或任何格式都没问题)。 I've found a lot of lubridate literature on breaking up dates, but am looking for how to put them together. 我发现了大量有关分手日期的lubridate文献,但我正在寻找如何将它们组合在一起。

As simple as it sounds: 听起来很简单:

year    day    
2008    1
2008    2
2008    3
2008    4

to

year    day    date
2008    1    2008-1-1
etc.

You could use base dates rather than lubridate if you like 如果你愿意,你可以使用基准日期而不是润滑

If this is your sample data 如果这是您的样本数据

dd<-data.frame(
    year = rep(2008,4), 
    day = 1:4
)

Then you can run 然后你就可以跑了

years <- unique(dd$year)
yearstarts <- setNames(as.Date(paste0(years, "-01-01")), years)
newdates <- yearstarts[as.character(dd$year)] + dd$day - 1

Which produces 哪个产生

cbind(dd, newdates)

#   year day   newdates
# 1 2008   1 2008-01-01
# 2 2008   2 2008-01-02
# 3 2008   3 2008-01-03
# 4 2008   4 2008-01-04

This works because the base Date class stores the number of days since a particular sentinel value. 这是有效的,因为基本Date类存储自特定sentinel值以来的天数。 So you when you add 1, you are adding one day to the current date. 因此,当您添加1时,您将在当前日期添加一天。 Here I assumed you may have multiple years to I make sure to correctly calculate the Date value for the first day of each year. 在这里,我假设您可能有多年的时间,我确保正确计算每年第一天的日期值。

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

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