R: how to access a tibble in a tibble?

2020-05-01 04:29发布

问题:

I am reading Hadley's: http://r4ds.had.co.nz/tibbles.html

However, I am still having difficulty referencing a tibble in a tibble.

> library(tidyquant)
> f <- tq_get("F", get="key.ratios")
> f
# A tibble: 7 x 2
            section               data
              <chr>             <list>
1        Financials <tibble [150 x 5]>
2     Profitability <tibble [170 x 5]>
3            Growth <tibble [160 x 5]>
4         Cash Flow  <tibble [50 x 5]>
5  Financial Health <tibble [240 x 5]>
6 Efficiency Ratios  <tibble [80 x 5]>
7  Valuation Ratios  <tibble [40 x 5]>

> f["Financials"]
Error: Column `Financials` not found

> f[["Financials"]]
NULL

> f$Financials
NULL
Warning message:
Unknown or uninitialised column: 'Financials'. 

> f$data[[f$section == 'Financials']]
Error in f$data[[f$section == "Financials"]] : 
  attempt to select less than one element in integerOneIndex

> f$data[[1]]$Financials
NULL
Warning message:
Unknown or uninitialised column: 'Financials'. 

回答1:

From tidyquant's documentation, using tq_get(symbol, get = "key.ratios") returns a nested tibble. Inside the tibble's "data" column are other tables with columns: section, sub.section, group, category, and date.

You were originally trying to access a column called "Financials" in the main data frame, but no such column exists (it has only "section" and "data"). "Financials" is, instead, an element (row) of the "section" column. I think instead you want:

filter(f, section == "Financials") %>% unnest()