将日期从 31-May-2020 转换为 R 中的时间序列数据

时间:2021-06-25 18:05:30

标签: 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"))

2 个答案:

答案 0 :(得分:3)

我们必须指定 format。默认情况下,格式为 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.

答案 1 :(得分:2)

我们也可以使用 lubridate 包函数。由于月份存储为缩写的月份名称,因此我们在此处使用 %b 而不是 %m

library(lubridate)

df %>%
  mutate(Date = as_date(Date, format = "%d-%b-%Y"))

# A tibble: 6 x 7
  Date       Price  Open  High   Low Vol.    `Change %`
  <date>     <dbl> <dbl> <dbl> <dbl> <chr>   <chr>     
1 2020-05-31 7213. 7051. 7339. 7150. 307.44M 2.30%     
2 2020-06-01 7289. 7213. 7289. 7202. 349.59M 1.05%     
3 2020-06-02 7285. 7289. 7321. 7278. 343.52M -0.05%    
4 2020-06-03 7222. 7285. 7312. 7202. 286.85M -0.86%    
5 2020-06-04 7208. 7222. 7208. 7129. 234.18M -0.20%    
6 2020-06-07 7268. 7208. 7278. 7234. 225.87M 0.83%     
相关问题