[英]Accessing grouping variables in purrr::map() with nested dataframes
我將tidyr::nest()
與purrr::map()
(-family)結合使用,將data.frame
分為幾組,然后對每個子集做一些花哨的東西。 考慮下面的示例, 請忽略以下事實:我不需要nest()
和map()
來執行此操作 (這是一個過於簡化的示例):
library(dplyr)
library(purrr)
library(tidyr)
mtcars %>%
group_by(cyl) %>%
nest() %>%
mutate(
wt_mean = map_dbl(data,~mean(.x$wt))
)
# A tibble: 8 x 4
cyl gear data cly2
<dbl> <dbl> <list> <dbl>
1 6 4 <tibble [4 x 9]> 6
2 4 4 <tibble [8 x 9]> 4
3 6 3 <tibble [2 x 9]> 6
4 8 3 <tibble [12 x 9]> 8
5 4 3 <tibble [1 x 9]> 4
6 4 5 <tibble [2 x 9]> 4
7 8 5 <tibble [2 x 9]> 8
8 6 5 <tibble [1 x 9]> 6
通常,當我執行這種類型的操作時,需要訪問map()
的分組變量(在這種情況下為cyl
map()
。 但是這些分組變量顯示為向量,其長度與嵌套數據框中的行數相對應,因此不容易使用。
有沒有辦法可以執行以下操作? 我希望將wt
的平均值除以每組 (即行)的圓柱數( cyl
)。
mtcars %>%
group_by(cyl,gear) %>%
nest() %>%
mutate(
wt_mean = map_dbl(data,~mean(.x$wt)/cyl)
)
Error in mutate_impl(.data, dots) :
Evaluation error: Result 1 is not a length 1 atomic vector.
從map
通話中刪除cyl
:
mtcars %>%
group_by(cyl,gear) %>%
nest() %>%
mutate(
wt_mean = map_dbl(data, ~mean(.x$wt)) / cyl
)
# A tibble: 8 x 4
cyl gear data wt_mean
<dbl> <dbl> <list> <dbl>
1 6 4 <tibble [4 x 9]> 0.516
2 4 4 <tibble [8 x 9]> 0.595
3 6 3 <tibble [2 x 9]> 0.556
4 8 3 <tibble [12 x 9]> 0.513
5 4 3 <tibble [1 x 9]> 0.616
6 4 5 <tibble [2 x 9]> 0.457
7 8 5 <tibble [2 x 9]> 0.421
8 6 5 <tibble [1 x 9]> 0.462
map_dbl
將cyl
視為長度為8的向量,因為nest
從data.frame
刪除了組。 在map_*
函數調用中使用cyl
(如OP的示例)會產生8個長度為8的向量。
兩者都具有與上述相同的結果,但根據OP的規范,將分組的變量保留在map_*
調用中:
nest
后重新分組 mtcars %>%
group_by(cyl,gear) %>%
nest() %>%
group_by(cyl, gear) %>%
mutate(wt_mean = map_dbl(data,~mean(.x$wt)/cyl))
map2
用於遍歷cyl
mtcars %>%
group_by(cyl,gear) %>%
nest() %>%
mutate(wt_mean = map2_dbl(data, cyl,~mean(.x$wt)/ .y))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.