年份列到时间序列[重复]

时间:2022-06-23 12:32:32

This question already has an answer here:

这个问题在这里已有答案:

OK, this should be really simple but I'm not 'getting it.' I have a data frame with a column "Year" that I want to convert to a time series, but the format is tripping me up. How do I convert the "Year" value to a date, with the actual date being the end of each respective year (e.g. 2015 -> December 31st 2015)?

好吧,这应该很简单,但我不是'得到它'。我有一个带有“Year”列的数据框,我希望将其转换为时间序列,但格式让我感到沮丧。如何将“年”值转换为日期,实际日期为每个年份的结束(例如2015年 - > 2015年12月31日)?

  Year   Production
1 1900     38400000
2 1901     43400000
3 1902     49000000
4 1903     44100000
5 1904     49800000

Goal is to get this to a time series data frame. (e.g. xts)

目标是将其转换为时间序列数据框架。 (例如xts)

It is not quite the same as a previous question that converted a vector of years to dates. "Convert four digit year values to date type". Goal is to index the data by date, converting it to xts or similar object.

它与之前将年代矢量转换为日期的问题并不完全相同。 “将四位数年份值转换为日期类型”。目标是按日期索引数据,将其转换为xts或类似对象。

Edited:
This was the final solution:

编辑:这是最终的解决方案:

df <- xts(x = df_original, order.by = as.Date(paste0(df_original[,1], "-12-31")))

whereby the "[,1]" indicates the first column of the original data frame.

其中“[,1]”表示原始数据帧的第一列。

2 个解决方案

#1


0  

If you want each full date to be 31 December, you could use paste along with as.Date to cast to a date:

如果您希望每个完整日期为12月31日,则可以使用粘贴和as.Date来转换为日期:

df$date <- as.Date(paste0(df$Year, "-12-31"))

#2


0  

In addition to Tim Biegeleisen's answer, I will just add another way

除了Tim Biegeleisen的回答,我还会添加另一种方式

df$final_date <- as.Date(ISOdate(df$Year, 12, 31))

#1


0  

If you want each full date to be 31 December, you could use paste along with as.Date to cast to a date:

如果您希望每个完整日期为12月31日,则可以使用粘贴和as.Date来转换为日期:

df$date <- as.Date(paste0(df$Year, "-12-31"))

#2


0  

In addition to Tim Biegeleisen's answer, I will just add another way

除了Tim Biegeleisen的回答,我还会添加另一种方式

df$final_date <- as.Date(ISOdate(df$Year, 12, 31))