xts
首先格式化,然后转换为数据帧——后者的转换通常比
ts
对象下面的操作相当简单——将文本提取到新列中。
library(xts)
library(tidyverse)
tsx <- as.xts(datasets::Seatbelts)
df <- data.frame(date=index(tsx), coredata(tsx)) %>%
mutate(date_chr = as.character(date),
month = substr(date, 1, 3),
year = substr(date, 5, 8))
date DriversKilled drivers front rear kms PetrolPrice VanKilled law date_chr month year
1 Jan 1969 107 1687 867 269 9059 0.1029718 12 0 Jan 1969 Jan 1969
2 Feb 1969 97 1508 825 265 7685 0.1023630 6 0 Feb 1969 Feb 1969
3 Mar 1969 102 1507 806 319 9963 0.1020625 12 0 Mar 1969 Mar 1969
4 Apr 1969 87 1385 814 407 10955 0.1008733 8 0 Apr 1969 Apr 1969
5 May 1969 119 1632 991 454 11823 0.1010197 10 0 May 1969 May 1969
6 Jun 1969 106 1511 945 427 12391 0.1005812 13 0 Jun 1969 Jun 1969