nestしたデータフレームの扱い
nestしたデータフレームを扱い方(メモ用)
library(tidyverse) iris %>% group_by(Species) %>% nest() %>% mutate(data = map2(data, Species, ~mutate(.x, Species_index = as.numeric(.y)))) %>% mutate(id = seq(1,3)) %>% mutate(data = map2(data, id, ~slice(.x, seq.int(.y)))) %>% mutate(MeanSepalLength = map_dbl(data, ~pull(.x, Sepal.Length) %>% mean))
上記の結果以下のデータを得ることができる。
Species data id MeanSepalLength <fct> <list> <int> <dbl> 1 setosa <tibble [1 x 5]> 1 5.1 2 versicolor <tibble [2 x 5]> 2 6.7 3 virginica <tibble [3 x 5]> 3 6.40