R のbigrquery
ライブラリを使用して BQ データベースから R にデータをロードしています。
dput(my_df_from_bq)
structure(list(season = c("2019", "2019", "2017", "2018", "2018"
), o_or_d = c("Offense", "Defense", "Offense", "Offense", "Defense"
), chances = list(list(num_ato_chances = 6L, ato_pts_scored = 4L,
ato_ppp = 0.66667, num_ato_chances_pctile = 0.272955974842767,
ato_ppp_pctile = 0.335849056603774), list(num_ato_chances = 7L,
ato_pts_scored = 2L, ato_ppp = 0.28571, num_ato_chances_pctile = 0.534591194968553,
ato_ppp_pctile = 0.913207547169811), list(num_ato_chances = 5L,
ato_pts_scored = 2L, ato_ppp = 0.4, num_ato_chances_pctile = 0.147118921127912,
ato_ppp_pctile = 0.177768696362893), list(num_ato_chances = 1L,
ato_pts_scored = 0L, ato_ppp = 0, num_ato_chances_pctile = 0,
ato_ppp_pctile = 0), list(num_ato_chances = 6L, ato_pts_scored = 8L,
ato_ppp = 1.33333, num_ato_chances_pctile = 0.70093839249286,
ato_ppp_pctile = 0.165646674826601)), dribbles = list(list(
dribbles = 928L, dribbles_pctile = 0.437735849056604), list(
dribbles = 1040L, dribbles_pctile = 0.113207547169811), list(
dribbles = 771L, dribbles_pctile = 0.0469963220269718), list(
dribbles = 735L, dribbles_pctile = 0.00489596083231334),
list(dribbles = 1049L, dribbles_pctile = 0.103223174214606))), row.names = c(NA,
-5L), class = c("tbl_df", "tbl", "data.frame"))
> my_df_from_bq
# A tibble: 5 x 4
season o_or_d chances dribbles
<chr> <chr> <list> <list>
1 2019 Offense <named list [5]> <named list [2]>
2 2019 Defense <named list [5]> <named list [2]>
3 2017 Offense <named list [5]> <named list [2]>
4 2018 Offense <named list [5]> <named list [2]>
5 2018 Defense <named list [5]> <named list [2]>
BQ からロードしているテーブルには、ネストされた構造体が多数含まれています。その結果、bigrquery ドキュメント自体が、ネストされた値が名前付きリストを含むリスト列になることを示しているため、データフレームのこの構造は期待どおりです。
ただし、これをフラットにしたいと思います。リストには、、my_df_from_bq$chances[[1]]$
などの値が含まれていることがわかります。したがって、列名が次のようになるように、このデータフレームをフラット化したいと思います。num_ato_chances
ato_pts_scored
ato_ppp
- シーズン
- o_or_d
- chances_num_ato_chances
- chances_ato_chances_pg
- chances_ato_ppp
- ...
- dribbles_dribbles
- dribbles_dribbles_pctile
...ここで、リスト名は各リスト内の値と連結されます。