読者です 読者をやめる 読者になる 読者になる

メモ:purrr::map(x, "要素名")よりはpurrr::transpose(x)$要素名

transpose()はやい。

library(purrr)

x <- rerun(10000, list(value = "1", type = "a"))

microbenchmark::microbenchmark(
  transpose(x)$type,
  map_chr(x, "type"),
  as.character(map(x, "type")),
  flatten_chr(map(x, "type"))
)
#> Unit: microseconds
#>                          expr       min        lq       mean     median         uq       max neval
#>             transpose(x)$type   330.272   425.284   449.4186   438.1235   454.5195  1174.125   100
#>            map_chr(x, "type") 18898.978 20167.522 21312.4949 20787.3745 22039.3265 34503.928   100
#>  as.character(map(x, "type")) 18883.966 19899.868 22092.4028 20954.4855 21711.2270 92734.888   100
#>   flatten_chr(map(x, "type")) 19327.620 20462.436 21531.9756 21252.9545 22271.2275 30534.740   100

もうちょい複雑な例。

x <- purrr::rerun(1000, list(a = list(value = "1", type = "a"),
                             b = list(value = "2", type = "b"),
                             c = list(value = "3", type = "c")))
microbenchmark::microbenchmark(
  bind_cols(map(transpose(x) , ~ flatten_chr(transpose(.)$type))),
  bind_rows(map(x, ~ map(., "type")))
)
#> Unit: microseconds
#>                                                           expr       min        lq       mean
#>  bind_cols(map(transpose(x), ~flatten_chr(transpose(.)$type)))   355.161   395.457   474.5605
#>                             bind_rows(map(x, ~map(., "type"))) 35888.226 39226.500 41128.6330
#>     median         uq       max neval
#>    448.396   550.7165   713.482   100
#>  40626.007 42855.7380 61294.270   100