Andy
Andy

Reputation: 11

Cannot find function Split_by in R in purrr package

I remember using this function split_by before from the package purrr. Now when I try to access it, it says could not find cunction Split_by. I tried doing an ls on the package purrr and I couldnt find the function in there. Is there any alternative that serves the purpose in the package?

Upvotes: 1

Views: 1033

Answers (2)

moodymudskipper
moodymudskipper

Reputation: 47340

See here for purrr 0.2.3

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

order_by(), sort_by() and split_by() have been removed. order_by() conflicted with dplyr::order_by() and the complete family doesn’t feel that useful. Use tibbles instead (#217).

Here is the original code from purrr 0.2.2:

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

And the original example:

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

Using tibbles instead

I understand the direction "use tibbles instead" this way :

Your list has several items sharing the same structure, thus list is not the appropriate structure, you could convert to a tibble to respect the tidy rules of "one row by observation, one column by variable", following previous example:

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

Then you can split it :

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]>

Or use dplyr::group_by (and keep it cleaner regarding tidy principles) :

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

Upvotes: 1

Mike Stanley
Mike Stanley

Reputation: 1480

split_by was deprecated in version 0.2.3 - see the release notes

The functionality is now in pluck, but you can pass multiple arguments - from the pluck docs:

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"

Upvotes: 0

Related Questions