如何创建包含嵌套 xts 对象的列 - 雅虎数据?

How to create a column containing nested xts object - yahoo data?

您好,我在不同股票的数据框中有来自雅虎的数据(列符号)。 我想创建每只股票 1 行的数据框(tibble),其中包含一列 嵌套的股票数据作为 xts 对象。添加了结果图片和可重现示例。任何帮助表示赞赏

library(purrr)
library(tidyverse)
library(tidyr)




  df<-structure(list(symbol = c("AAPL", "AAPL", "AAPL", "AAPL", "AAPL", 
                                      "AMZN", "AMZN", "AMZN", "AMZN", "AMZN", "MSFT", "MSFT", "MSFT", 
                                      "MSFT", "MSFT"), date = structure(c(18295, 16700, 17571, 18305, 
                                                                          18086, 17834, 17696, 17438, 16850, 18016, 18376, 17935, 18085, 
                                                                          17626, 17724), class = "Date"), adjusted = c(76.636299, 26.198639, 
                                                                                                                       37.847511, 80.852463, 49.627182, 1530.420044, 1723.859985, 961.349976, 
                                                                                                                       534.900024, 1926.52002, 173.645462, 103.308533, 134.968887, 89.195686, 
                                                                                                                       101.034645)), row.names = c(NA, -15L), class = c("tbl_df", "tbl", 
                                                                                                                                                                        "data.frame"))

df%>%group_by(symbol)%>%
  nest()%>%
  mutate(xts_obj=map(data,~as.xts(order_by=.$date)))

在这里,我们可能需要通过进入 xts object

来删除 'date' 列
library(dplyr)
library(xts)
library(purrr)
ndf <- df %>% 
     group_by(symbol) %>%
     nest %>% 
     mutate(xts_obj = map(data, ~ xts(.x %>% select(-date), order.by = .x$date)))
ndf
# A tibble: 3 x 3
# Groups:   symbol [3]
#  symbol data             xts_obj      
#  <chr>  <list>           <list>       
#1 AAPL   <tibble [5 × 2]> <xts [5 × 1]>
#2 AMZN   <tibble [5 × 2]> <xts [5 × 1]>
#3 MSFT   <tibble [5 × 2]> <xts [5 × 1]>

或者通过仅选择 numeric

使其更具动态性
df %>% 
    group_by(symbol) %>% 
    nest %>%
    mutate(xts_obj = map(data, ~ .x %>% 
                select(where(is.numeric)) %>% 
                xts(., order.by = .x$date)))

ndf$xts_obj[[1]]
#           adjusted
#2015-09-22 26.19864
#2018-02-09 37.84751
#2019-07-09 49.62718
#2020-02-03 76.63630
#2020-02-13 80.85246

根据 OP 的图像,它将 xts_obj 列显示为具有 0 个元素的 list

ndf0$xts_obj[[1]]
#Data:
#numeric(0)