[英]using purrr to map dplyr::select
我有一個數據框,其中包含一堆嵌套的數據框,我想將dplyr :: select應用於每個嵌套數據框。 這是一個例子
library(tidyverse)
mtcars %>%
group_by(cyl) %>%
nest %>%
mutate(data2 = ~map(data, dplyr::select(.,-mpg)))
我認為這會產生一個包含三列的數據框。 cyl
:柱面數, data
:嵌套數據, data2
:數據相同,除了每個元素都沒有mpg列。
相反,R崩潰:
*** caught segfault *** address 0x7ffc1e445000, cause 'memory not mapped' Traceback: 1: .Call(`_dplyr_mutate_impl`, df, dots) 2: mutate_impl(.data, dots) 3: mutate.tbl_df(., data2 = ~map(data, dplyr::select(., -mpg))) 4: mutate(., data2 = ~map(data, dplyr::select(., -mpg))) 5: function_list[[k]](value) 6: withVisible(function_list[[k]](value)) 7: freduce(value, `_function_list`) 8: `_fseq`(`_lhs`) 9: eval(quote(`_fseq`(`_lhs`)), env, env) 10: eval(quote(`_fseq`(`_lhs`)), env, env) 11: withVisible(eval(quote(`_fseq`(`_lhs`)), env, env)) 12: mtcars %>% group_by(cyl) %>% nest %>% mutate(data2 = ~map(data, dplyr::select(., -mpg))) Possible actions: 1: abort (with core dump, if enabled) 2: normal R exit 3: exit R without saving workspace 4: exit R saving workspace
如果我在嵌套之前應用select操作,我意識到我可以得到我想要的列,但這與我的真實問題不太相似。 有人可以向我解釋我在這里做錯了什么嗎? 謝謝你的建議。
你需要搬家~
從map
來select
; 或者將評論用作@Russ; ~
用於當函數(在這種情況下purrr::map
)接受的公式作為參數:
mtcars %>%
group_by(cyl) %>%
nest %>%
mutate(data2 = map(data, ~ select(., -mpg)))
# A tibble: 3 x 3
# cyl data data2
# <dbl> <list> <list>
#1 6 <tibble [7 × 10]> <tibble [7 × 9]>
#2 4 <tibble [11 × 10]> <tibble [11 × 9]>
#3 8 <tibble [14 × 10]> <tibble [14 × 9]>
這里有兩種方式:一種是跳過嵌套,只是使用do
,一種是嵌套然后使用map
。 unnest(data2)
然后將其恢復為常規數據幀。 有一點要注意的是,我包括-cyl
內select
在第一個例子; 這是因為否則的話,你最終cyl
從嵌套的數據幀兩次,從分組列各一次。
除了個人喜好之外,我不確定其中一種方法是否優於另一種方式。
library(tidyverse)
mtcars %>%
group_by(cyl) %>%
do(data2 = select(., -mpg, -cyl)) %>%
unnest(data2)
#> # A tibble: 32 x 10
#> cyl disp hp drat wt qsec vs am gear carb
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 4 108 93 3.85 2.32 18.6 1 1 4 1
#> 2 4 147. 62 3.69 3.19 20 1 0 4 2
#> 3 4 141. 95 3.92 3.15 22.9 1 0 4 2
#> 4 4 78.7 66 4.08 2.2 19.5 1 1 4 1
#> 5 4 75.7 52 4.93 1.62 18.5 1 1 4 2
#> 6 4 71.1 65 4.22 1.84 19.9 1 1 4 1
#> 7 4 120. 97 3.7 2.46 20.0 1 0 3 1
#> 8 4 79 66 4.08 1.94 18.9 1 1 4 1
#> 9 4 120. 91 4.43 2.14 16.7 0 1 5 2
#> 10 4 95.1 113 3.77 1.51 16.9 1 1 5 2
#> # ... with 22 more rows
mtcars %>%
group_by(cyl) %>%
nest() %>%
mutate(data2 = map(data, function(df) select(df, -mpg))) %>%
unnest(data2)
# same output
另一種解決方案是將-mpg
“按-mpg
”傳遞給map()
,這將正確地將其傳遞給select()
。
mtcars %>%
group_by(cyl) %>%
nest %>%
mutate(data2 = map( data, select, -mpg ))
在R 3.6.1
使用dplyr 0.8.3
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.