Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow keeping names with squash, similar to unlist. #168

Closed
NGaffney opened this issue Jun 6, 2017 · 1 comment
Closed

Allow keeping names with squash, similar to unlist. #168

NGaffney opened this issue Jun 6, 2017 · 1 comment
Labels

Comments

@NGaffney
Copy link

NGaffney commented Jun 6, 2017

Currently when squashing a nested list it only maintains the innermost names, discarding information which can be important and potentially causing name collision errors.

library(purrr)
library(rlang)

pets <- list(
  pet = list(
    name = "Fluffy"
  ),
  coat = list(
    colour = "blue",
    pattern = "mearle"
  ),
  eyes = list(
    colour = "blue"
  )
)

squash(pets)
## $name
## [1] "Fluffy"
## 
## $colour
## [1] "blue"
## 
## $pattern
## [1] "mearle"
## 
## $colour
## [1] "blue"

On the other hand unlist has the use.names argument which keeps names by concatenating the names of each level.

pets %>% 
  unlist %>% 
  as.list
## $pet.name
## [1] "Fluffy"
## 
## $coat.colour
## [1] "blue"
## 
## $coat.pattern
## [1] "mearle"
## 
## $eyes.colour
## [1] "blue"

It would be nice to have an equivalent option for squash rather than having to collect and then manually set the names after squashing, like below.

recursive_names <- function(x, parent_name = NULL) {
  if (is.list(x)) {
    if (!is.null(parent_name)) {
      x_names <- paste(parent_name, names(x), sep = "_")
    } else {
      x_names <- names(x)
    }
    
    map2(
      x,
      x_names,
      recursive_names
    ) %>% 
      reduce(c)
  } else {
    return(parent_name)
  }
}

squash_named <- function(x) {
  setNames(
    squash(x),
    recursive_names(x)
  ) 
}

pets %>% 
  squash_named()
## $pet_name
## [1] "Fluffy"
## 
## $coat_colour
## [1] "blue"
## 
## $coat_pattern
## [1] "mearle"
## 
## $eyes_colour
## [1] "blue"
@lionel- lionel- added the vector label Mar 5, 2018
@lionel-
Copy link
Member

lionel- commented Sep 3, 2018

I think you'd use this (once implemented): tidyverse/purrr#525

@lionel- lionel- closed this as completed Sep 3, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants