2017-04-22 30 views
1

我自學的是R tidyverse purr()包,並且在嵌套數據幀列上實現map()時遇到問題。有人能解釋我錯過了什麼嗎?在一列嵌套數據幀上實現map()

使用基礎R ChickWeight數據集作爲一個例子,我可以很容易地得到觀察次數爲下飲食#1中的每個時間點,如果我對飲食#1第一個過濾器,像這樣:

library(tidyverse) 
ChickWeight %>% 
    filter(Diet == 1) %>% 
    group_by(Time) %>% 
    summarise(counts = n_distinct(Chick)) 

這是很大,但我想立即爲每種飲食做到這一點,我認爲嵌套數據和map()迭代將是一個很好的方法。 這是我做過什麼:

example <- ChickWeight %>% 
    nest(-Diet) 

實現那麼這個地圖功能實現是我的目標爲:

map(example$data, ~ .x %>% group_by(Time) %>% summarise(counts = n_distinct(Chick))) 

然而,當我嘗試使用管道把它在實現這個相同的命令原始數據幀的另一列失敗。

example %>% 
    mutate(counts = map(data, ~ .x %>% group_by(Time) %>% summarise(counts = n_distinct(Chick)))) 
Error in eval(substitute(expr), envir, enclos) : 
    variable 'Chick' not found 

爲什麼會發生這種情況?


我也嘗試了它在數據框分裂成一個列表,它沒有工作。

ChickWeight %>% 
    split(.$Diet) %>% 
    map(data, ~ .x %>% group_by(Time) %>% summarise(counts = n_distinct(Chick))) 

回答

4

因爲你使用dplyr dplyr NSE的內部非標準評價,它變得無所適從的環境中尋找Chick。這可能是一個錯誤,真的,但它可以與開發版的新.data代名詞,它指定到哪裏尋找避免:

library(tidyverse) 

ChickWeight %>% 
    nest(-Diet) %>% 
    mutate(counts = map(data, 
         ~.x %>% group_by(Time) %>% 
          summarise(counts = n_distinct(.data$Chick)))) 
#> # A tibble: 4 × 3 
#>  Diet    data   counts 
#> <fctr>    <list>   <list> 
#> 1  1 <tibble [220 × 3]> <tibble [12 × 2]> 
#> 2  2 <tibble [120 × 3]> <tibble [12 × 2]> 
#> 3  3 <tibble [120 × 3]> <tibble [12 × 2]> 
#> 4  4 <tibble [118 × 3]> <tibble [12 × 2]> 

要管它在列表中,留下map空白的第一個參數通過列表中的一個要迭代:

ChickWeight %>% 
    split(.$Diet) %>% 
    map(~ .x %>% group_by(Time) %>% summarise(counts = n_distinct(Chick))) %>% .[[1]] 

#> # A tibble: 12 × 2 
#>  Time counts 
#> <dbl> <int> 
#> 1  0  20 
#> 2  2  20 
#> 3  4  19 
#> 4  6  19 
#> 5  8  19 
#> 6  10  19 
#> 7  12  19 
#> 8  14  18 
#> 9  16  17 
#> 10 18  17 
#> 11 20  17 
#> 12 21  16 

一個更簡單的辦法是隻需兩列組:

ChickWeight %>% group_by(Diet, Time) %>% summarise(counts = n_distinct(Chick)) 

#> Source: local data frame [48 x 3] 
#> Groups: Diet [?] 
#> 
#>  Diet Time counts 
#> <fctr> <dbl> <int> 
#> 1  1  0  20 
#> 2  1  2  20 
#> 3  1  4  19 
#> 4  1  6  19 
#> 5  1  8  19 
#> 6  1 10  19 
#> 7  1 12  19 
#> 8  1 14  18 
#> 9  1 16  17 
#> 10  1 18  17 
#> # ... with 38 more rows 
+0

你的意思是從https://github.com/tidyverse/tidyverse開發的版本嗎?我只是重新安裝它(版本1.1.1.9000),它找不到'.data'。我得到'mutate_impl(.data,dots):object'.data'not found'錯誤。 –

+1

Devel dplyr,你可以從這裏安裝(https://github.com/hadley/dplyr/)。 – alistaire