提取变量内的嵌入式数据框

时间:2018-09-05 15:50:48

标签: r json

我的问题与以下问题非常相似:R extracting lists within dataframes

我试图取消嵌套在名为“ Obs”的变量中的数据帧的嵌套,但是无法弄清为什么unnest命令不起作用。

    library(IMFData)

    # Pull data from the CDIS database in the IMF Data
    cdis <- imf_data(database_id = 'CDIS', indicator = 'IIWDA_DV_BP6_USD',
                        country = c('CN', 'GB'), freq = 'A',
                        start = 2013, end = current_year(),  return_raw = T)

   # Extract the data
    cdis_df <- cdis$CompactData$DataSet$Series

   # Remove null observations
    cdis_df <- cdis_df %>%
      filter(Obs != 'NULL')

   # Unnest the obs column
    unnested_cdis <- cdis_df %>%
      unnest(Obs)

1 个答案:

答案 0 :(得分:1)

强制Obs列以整齐data_frame s(也称为tibble s)。然后unnest可以正常工作:

cdis_df %>% mutate_at( "Obs", purrr::map, as_data_frame ) %>% unnest
#   @FREQ @REF_AREA       @INDICATOR @COUNTERPART_AREA @UNIT_MULT @TIME_FORMAT
# 1     A        CN IIWDA_DV_BP6_USD                PH          6          P1Y
# 2     A        CN IIWDA_DV_BP6_USD                PH          6          P1Y
# 3     A        CN IIWDA_DV_BP6_USD                PH          6          P1Y
# 4     A        CN IIWDA_DV_BP6_USD                PH          6          P1Y
# 5     A        CN IIWDA_DV_BP6_USD                PL          6          P1Y
# 6     A        CN IIWDA_DV_BP6_USD                PL          6          P1Y
#   @TIME_PERIOD        @OBS_VALUE @OBS_STATUS
# 1         2013 0.791124420227856        <NA>
# 2         2014                 0        <NA>
# 3         2015                 0        <NA>
# 4         2016                 0        <NA>
# 5         2013  8.96414342629482        <NA>
# 6         2014  12.4600821167883        <NA>