Search code examples
rlistpurrrsimplifyaccumulate

Transform an atomic vector to list (inverse of purrr::simplify())


TLDR: I need a simple way to transform c(a = 1, a = 3, a = 6) into list(c(a = 1), c(a = 3), c(a = 6)).

Longer version: I am using the function purrr::accumulate(), where the output of each element is an atomic vector of length greater or equal to one. When the length is one, purrr::accumulate() simplifies the whole output to an atomic vector, instead of a list.

Is there a simple way to undo or avoid this? Unfortunately, as.list() does not give me what I want.

Simple example to illustrate:

purrr::accumulate(2:3, `+`, .init = c(a=1, b=2))

gives me

list(c(a = 1, b = 2), c(a = 3, b = 4), c(a = 6, b = 7))

as expected. However,

purrr::accumulate(2:3, `+`, .init = c(a=1))

gives me

c(a = 1, a = 3, a = 6)

when I instead want

list(c(a = 1), c(a = 3), c(a = 6))

Solution

  • You could try

    c(a = 1, a = 3, a = 6) %>% map(~setNames(.x, nm = "a")) 
    
    $a
    a 
    1 
    
    $a
    a 
    3 
    
    $a
    a 
    6
    

    or you can also remove the list names with set_names()

    c(a = 1, a = 3, a = 6) %>% map(~setNames(.x, nm = "a")) %>% 
      set_names("")
    
    [[1]]
    a 
    1 
    
    [[2]]
    a 
    3 
    
    [[3]]
    a 
    6