如何将 rownames_to_column 与日期一起使用
How to use rownames_to_column with dates
我正在尝试将我的 yahoo price 下载转换为“整洁”格式,但在下面的 reprex 中,日期失去了它们的格式并被转换为行号。换句话说,我如何将 xts 转换为 tibble 并保留日期?
prices <- getSymbols("QQQ", adjustOHLC = TRUE, auto.assign = FALSE) %>%
as_tibble() %>%
rownames_to_column(var = "Date")
head(prices)
我认为你应该在 .xts 上使用 index()
而不是在 tibble 上使用 rownames_to_column()
library(quantmod)
library(dplyr)
price.xts <-getSymbols("QQQ", adjustOHLC = TRUE, auto.assign = FALSE)
price<-as_tibble(price.xts)
price$Date <-index(price.xts)
head(price)
tail(price)
要将其全部保存在单个 tidyverse 管道中,只需先转换为数据框即可:
library(quantmod)
library(tibble)
getSymbols("QQQ", adjustOHLC = TRUE, auto.assign = FALSE) %>%
as.data.frame() %>%
rownames_to_column(var = "Date") %>%
as_tibble()
#> # A tibble: 3,419 x 7
#> Date QQQ.Open QQQ.High QQQ.Low QQQ.Close QQQ.Volume QQQ.Adjusted
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 2007-01-03 43.5 44.1 42.5 43.2 167689500 38.3
#> 2 2007-01-04 43.3 44.2 43.2 44.1 136853500 39.1
#> 3 2007-01-05 44.0 44.0 43.5 43.8 138958800 38.9
#> 4 2007-01-08 43.9 44.1 43.6 43.9 106401600 38.9
#> 5 2007-01-09 44.0 44.3 43.6 44.1 121577500 39.1
#> 6 2007-01-10 44.0 44.7 43.8 44.6 121070100 39.6
#> 7 2007-01-11 44.7 45.2 44.7 45.1 174029800 40.0
#> 8 2007-01-12 45.0 45.3 45.0 45.3 104217300 40.2
#> 9 2007-01-16 45.3 45.4 45.1 45.3 95690500 40.1
#> 10 2007-01-17 45.1 45.3 44.8 44.9 127142600 39.8
#> # ... with 3,409 more rows
由 reprex package (v0.3.0)
于 2020 年 8 月 2 日创建
我正在尝试将我的 yahoo price 下载转换为“整洁”格式,但在下面的 reprex 中,日期失去了它们的格式并被转换为行号。换句话说,我如何将 xts 转换为 tibble 并保留日期?
prices <- getSymbols("QQQ", adjustOHLC = TRUE, auto.assign = FALSE) %>%
as_tibble() %>%
rownames_to_column(var = "Date")
head(prices)
我认为你应该在 .xts 上使用 index()
而不是在 tibble 上使用 rownames_to_column()
library(quantmod)
library(dplyr)
price.xts <-getSymbols("QQQ", adjustOHLC = TRUE, auto.assign = FALSE)
price<-as_tibble(price.xts)
price$Date <-index(price.xts)
head(price)
tail(price)
要将其全部保存在单个 tidyverse 管道中,只需先转换为数据框即可:
library(quantmod)
library(tibble)
getSymbols("QQQ", adjustOHLC = TRUE, auto.assign = FALSE) %>%
as.data.frame() %>%
rownames_to_column(var = "Date") %>%
as_tibble()
#> # A tibble: 3,419 x 7
#> Date QQQ.Open QQQ.High QQQ.Low QQQ.Close QQQ.Volume QQQ.Adjusted
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 2007-01-03 43.5 44.1 42.5 43.2 167689500 38.3
#> 2 2007-01-04 43.3 44.2 43.2 44.1 136853500 39.1
#> 3 2007-01-05 44.0 44.0 43.5 43.8 138958800 38.9
#> 4 2007-01-08 43.9 44.1 43.6 43.9 106401600 38.9
#> 5 2007-01-09 44.0 44.3 43.6 44.1 121577500 39.1
#> 6 2007-01-10 44.0 44.7 43.8 44.6 121070100 39.6
#> 7 2007-01-11 44.7 45.2 44.7 45.1 174029800 40.0
#> 8 2007-01-12 45.0 45.3 45.0 45.3 104217300 40.2
#> 9 2007-01-16 45.3 45.4 45.1 45.3 95690500 40.1
#> 10 2007-01-17 45.1 45.3 44.8 44.9 127142600 39.8
#> # ... with 3,409 more rows
由 reprex package (v0.3.0)
于 2020 年 8 月 2 日创建