I have a dataset downloaded from yahoo in R :
library(tidyquant)
symbol = c("DOW","TWTR","FB","GOOG","TSLA","NOK","AMZN","AAPL")
ASSETS = tq_get(symbol,
from = "2017-01-01",
to = "2022-02-01")
DATAWEB = ASSETS%>%
select(symbol,date,close,volume)
that look like this :
symbol date close volume
<chr> <date> <dbl> <dbl>
1 DOW 2019-03-20 49.8 2350800
2 DOW 2019-03-21 49.0 1764700
3 DOW 2019-03-22 48.6 844700
4 DOW 2019-03-25 49.2 440900
5 DOW 2019-03-26 48.8 504700
6 DOW 2019-03-27 50.1 1788600
7 DOW 2019-03-28 50.8 585400
8 DOW 2019-03-29 51.6 1769000
9 DOW 2019-04-01 53.5 19663400
10 DOW 2019-04-02 56.2 17414200
# ... with 9,667 more rows
# i Use `print(n = ...)` to see more rows
I want to convert the date column form date class object to dttm. How can I do it? Any help?
CodePudding user response:
as.POSIXct
converts it to dttm object like this:
library(tidyquant)
library(dplyr)
symbol = c("DOW","TWTR","FB","GOOG","TSLA","NOK","AMZN","AAPL")
ASSETS = tq_get(symbol,
from = "2017-01-01",
to = "2022-02-01")
DATAWEB = ASSETS%>%
select(symbol,date,close,volume) %>%
mutate(date = as.POSIXct(date))
DATAWEB
#> # A tibble: 9,677 × 4
#> symbol date close volume
#> <chr> <dttm> <dbl> <dbl>
#> 1 DOW 2019-03-20 01:00:00 49.8 2350800
#> 2 DOW 2019-03-21 01:00:00 49.0 1764700
#> 3 DOW 2019-03-22 01:00:00 48.6 844700
#> 4 DOW 2019-03-25 01:00:00 49.2 440900
#> 5 DOW 2019-03-26 01:00:00 48.8 504700
#> 6 DOW 2019-03-27 01:00:00 50.1 1788600
#> 7 DOW 2019-03-28 01:00:00 50.8 585400
#> 8 DOW 2019-03-29 01:00:00 51.6 1769000
#> 9 DOW 2019-04-01 02:00:00 53.5 19663400
#> 10 DOW 2019-04-02 02:00:00 56.2 17414200
#> # … with 9,667 more rows
#> # ℹ Use `print(n = ...)` to see more rows
Created on 2022-07-22 by the reprex package (v2.0.1)
CodePudding user response:
A possible solution, based on lubridate::as_datetime
:
library(dplyr)
DATAWEB %>%
mutate(date = lubridate::as_datetime(date))
#> # A tibble: 9,677 × 4
#> symbol date close volume
#> <chr> <dttm> <dbl> <dbl>
#> 1 DOW 2019-03-20 00:00:00 49.8 2350800
#> 2 DOW 2019-03-21 00:00:00 49.0 1764700
#> 3 DOW 2019-03-22 00:00:00 48.6 844700
#> 4 DOW 2019-03-25 00:00:00 49.2 440900
#> 5 DOW 2019-03-26 00:00:00 48.8 504700
#> 6 DOW 2019-03-27 00:00:00 50.1 1788600
#> 7 DOW 2019-03-28 00:00:00 50.8 585400
#> 8 DOW 2019-03-29 00:00:00 51.6 1769000
#> 9 DOW 2019-04-01 00:00:00 53.5 19663400
#> 10 DOW 2019-04-02 00:00:00 56.2 17414200
#> # … with 9,667 more rows
#> # ℹ Use `print(n = ...)` to see more rows