如何在Rstudio中转换日期格式

How to convert date format in Rstudio

我是 Rstudio 的初学者,我 运行 遇到了一个问题。我使用的时间序列的日期格式如下:

2015-01-01
2015-02-01
2015-03-01
2015-04-01
2015-05-01
2015-06-01
2015-07-01
2015-08-01
2015-09-01
2015-10-01
2015-11-01
2015-12-01

我不得不用这个来改变它:

dplyr::mutate(TimeSeries,
      year = lubridate::decimal_date(time),
      month= lubridate::month(time, label = T),
      month = factor(month, ordered=F))

现在,我的数据的日期格式如下:

2015.000
2015.085
2015.162  
2015.247 
2015.329 
2015.414
2015.496 
2015.581 
2015.666 
2015.748 
2015.833 
2015.915

我的问题是,我需要使用这种格式,但我需要知道月数。我不能只做模数,因为每年小数位的变化很小。谢谢!

只需从 lubridate::month 中删除 label 参数,然后您就不需要使用 factor(month, ordered=F) 除非您需要这个值作为一个因素:

dplyr::mutate(TimeSeries,
              year = lubridate::decimal_date(time),
              month= lubridate::month(time))

输出

         time     year month
1  2015-01-01 2015.000     1
2  2015-02-01 2015.085     2
3  2015-03-01 2015.162     3
4  2015-04-01 2015.247     4
5  2015-05-01 2015.329     5
6  2015-06-01 2015.414     6
7  2015-07-01 2015.496     7
8  2015-08-01 2015.581     8
9  2015-09-01 2015.666     9
10 2015-10-01 2015.748    10
11 2015-11-01 2015.833    11
12 2015-12-01 2015.915    12

数据

TimeSeries <- structure(list(time = structure(c(16436, 16467, 16495, 16526, 
16556, 16587, 16617, 16648, 16679, 16709, 16740, 16770), class = "Date")), class = "data.frame", row.names = c(NA, 
-12L))