r - 将2020年5月31日的日期格式转换为R中的时间序列数据

标签 r time-series

我的日期格式为 01-June-2020。我想将其转换为 R 中的时间序列数据。我尝试了 as.Date 但它返回 NAs

这是数据:

dput(head(TData))
structure(list(Date = c("31-May-20", "01-Jun-20", "02-Jun-20", 
"03-Jun-20", "04-Jun-20", "07-Jun-20"), Price = c(7213.03, 7288.81, 
7285.23, 7222.41, 7207.78, 7267.86), Open = c(7050.66, 7213.03, 
7288.81, 7285.23, 7222.41, 7207.78), High = c(7338.96, 7288.81, 
7321.36, 7311.85, 7207.78, 7277.7), Low = c(7149.71, 7202.14, 
7277.63, 7202.39, 7129.25, 7233.67), Vol. = c("307.44M", "349.59M", 
"343.52M", "286.85M", "234.18M", "225.87M"), `Change %` = c("2.30%", 
"1.05%", "-0.05%", "-0.86%", "-0.20%", "0.83%")), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

最佳答案

我们必须指定格式。默认情况下,格式为 YYYY-MM-DD%Y-%m-%d。在这里,它是 %d 2 位数字的日期,后跟字符缩写的月份 - %b 和 2 位数字的年份 - %y

TData$Date <- as.Date(TData$Date, '%d-%b-%y')

如果我们想创建时间序列数据,可以使用xts

library(lubridate)
library(xts)
library(dplyr)
TData %>% 
    mutate(Date  = dmy(Date)) %>% 
    select(Date, where(is.numeric)) %>% 
    {xts(.[-1], order.by = .$Date)}
             Price    Open    High     Low
2020-05-31 7213.03 7050.66 7338.96 7149.71
2020-06-01 7288.81 7213.03 7288.81 7202.14
2020-06-02 7285.23 7288.81 7321.36 7277.63
2020-06-03 7222.41 7285.23 7311.85 7202.39
2020-06-04 7207.78 7222.41 7207.78 7129.25
2020-06-07 7267.86 7207.78 7277.70 7233.67

或者可以使用tsibble

library(tsibble)
TData %>% 
    mutate(Date  = dmy(Date)) %>% 
    select(Date, where(is.numeric)) %>%
    as_tsibble(index = Date)

-输出

# A tsibble: 6 x 5 [1D]
  Date       Price  Open  High   Low
  <date>     <dbl> <dbl> <dbl> <dbl>
1 2020-05-31 7213. 7051. 7339. 7150.
2 2020-06-01 7289. 7213. 7289. 7202.
3 2020-06-02 7285. 7289. 7321. 7278.
4 2020-06-03 7222. 7285. 7312. 7202.
5 2020-06-04 7208. 7222. 7208. 7129.
6 2020-06-07 7268. 7208. 7278. 7234.

关于r - 将2020年5月31日的日期格式转换为R中的时间序列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68135407/

相关文章:

r - 如何获取 R 中每个因子变量的水平

给定多个输入的 R ggplot 直方图

r - 根据行值连接列名

python - 使用随机森林预测 future 发生的情况

python - 如何将一个系列的值合并到另一个系列

r - 基于R中特定类别的其他列计算百分比列

r - 如何将 ggrepel 与生存图 (ggsurvplot) 结合使用?

r - 为缺失数据插入行并进行插值

tensorflow - 如何在没有嵌入的情况下使用 tensorflow seq2seq?

r - 如何解析毫秒?