Skip to content

Mapping over trees #236

Closed
Closed

Description

@lionel-

at_bottom() would be like at_depth() but at bottom. Useful for tree structures.

Activity

  1. lionel- commented on Sep 1, 2016

    @lionel-
    MemberAuthor

    On that note I wonder if the following would be good UI:

    array_tree(x, ~last)
    array_tree(x, list(1, 2, ~last)
    
    x %>% at_depth(~last, f)
  2. lionel- commented on Sep 15, 2016

    @lionel-
    MemberAuthor

    Other useful idiom for tree structures: visit each node twice. Once on the way in, the second time on the way back. See https://stlab.adobe.com/group__asl__tutorials__forest.html

    The mapped function would get a boolean indicating if this is the second time we see the node.

  3. alistaire47 commented on Feb 10, 2017

    @alistaire47

    Would this map over the deepest level or all leaf nodes? The latter (or some other intelligible version of rapply) could be really useful for parsing deeply nested data coming from JSON or the like.

  4. lionel- commented on Feb 26, 2017

    @lionel-
    MemberAuthor
  5. lionel- commented on Feb 26, 2017

    @lionel-
    MemberAuthor

    @alistaire47 yes I was thinking at_bottom() would apply a function to leaves. We could have map_tree() to apply a function to all nodes, then at_bottom() would be implemented as:

    x %>% map_tree_if(is_atomic, fn)

    And maybe have map_tree_until(), which would not inspect further the nodes for which the predicate returns FALSE, which could be useful for applying a function to list-like S3 objects.

  6. changed the title [-]at_bottom()[/-] [+]Mapping over trees[/+] on Feb 26, 2017
  7. hadley commented on Mar 5, 2017

    @hadley
    Member

    What if instead of at_bottom(.x, .f) you simply did at_depth(.x, -1, .f)?

    And what if at_depth() was instead called modify_depth()? And to match the other modify() functions was called modify_depth()?

  8. hadley commented on Mar 5, 2017

    @hadley
    Member

    I also wonder about an option to at_depth() that gives you this behaviour:

      recurse <- function(x, depth) {
        if (depth > 1) {
          if (is.atomic(x)) {
            x
          } else {
            lapply(x, recurse, depth = depth - 1)
          }
        } else {
          lapply(x, .f, ...)
        }
      }

    So that if the list is ragged, you can choose to only operate on lists at a certain level, ignoring branches that aren't that deep.

  9. added a commit that references this issue on Jan 10, 2025
    3a38083
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    featurea feature request or enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions