2017-10-06 55 views
0

我記得使用這個函數split_by之前從包purrr。現在,當我嘗試訪問它時,它說無法找到連接點Split_by。我試着在包purrr上做一個ls,我找不到那裏的功能。有沒有其他方法可以在包裝中達到目的?找不到函數Split_by in R在purrr包

回答

0

看這裏爲purrr 0.2.3

https://cran.r-project.org/web/packages/purrr/news.html

order_by(),sort_by()和split_by()已被刪除。 order_by() 與dplyr :: order_by()衝突,並且整個系列不覺得 有用。改用t((#217)。

這裏是purrr 0.2.2原代碼:

split_by <- function(.x, .f, ...) { 
    vals <- map(.x, .f, ...) 
    split(.x, simplify_all(transpose(vals))) 
} 

和原來的例子:

l2 <- rerun(5, g = sample(2, 1), y = rdunif(5, 10)) 
l2 %>% split_by("g") %>% str() 

使用tibbles代替

我理解的方向「使用tibbles相反「這樣:

您的列表中有幾個項目共享相同的結構,因此名單是不是合適的結構,你可以轉換爲tibble尊重"one row by observation, one column by variable"整齊規則,以下前面的例子:

t2 <- as_tibble(transpose(l2)) %>% mutate(g=unlist(g)) 

然後你可以把它分解:

split(t2,t2$g) 

# $`1` 
# # A tibble: 3 x 2 
#   g   y 
#  <int> <list> 
# 1  1 <dbl [5]> 
# 2  1 <dbl [5]> 
# 3  1 <dbl [5]> 
# 
# $`2` 
# # A tibble: 2 x 2 
#   g   y 
#  <int> <list> 
# 1  2 <dbl [5]> 
# 2  2 <dbl [5]> 

或使用dplyr::group_by(並保持清潔整齊的有關原則):

t2 %>% group_by(g) %>% your_code 
+1

太棒了!非常感謝! – Andy

+0

我更新了以下哈德利的建議,以取代它。 –

0

split_by在0.2.3版本已過時 - 見the release notes

現在的功能是pluck,但你可以通過多個參數 - 從pluck文檔:

library(purrr) 
# pluck() supports integer positions, string names, and functions. 
# Using functions, you can easily extend pluck(). Let's create a 
# list of data structures: 
obj1 <- list("a", list(1, elt = "foobar")) 
obj2 <- list("b", list(2, elt = "foobaz")) 
x <- list(obj1, obj2) 

# And now an accessor for these complex data structures: 
my_element <- function(x) x[[2]]$elt 

# The accessor can then be passed to pluck: 
pluck(x, 1, my_element) 
#> [1] "foobar" 
pluck(x, 2, my_element) 
#> [1] "foobaz"