Meaning of error using . shorthand inside dplyr function

前端 未结 1 769
余生分开走
余生分开走 2020-12-19 07:35

I\'m getting a dplyr::bind_rows error. It\'s a very trivial problem, because I can easily get around it, but I\'d like to understand the meaning of the error me

相关标签:
1条回答
  • 2020-12-19 08:13

    As @aosmith noted in the comments it's due to the way magrittr parses the dot in this case :

    from ?'%>%':

    Using the dot-place holder as lhs

    When the dot is used as lhs, the result will be a functional sequence, i.e. a function which applies the entire chain of right-hand sides in turn to its input.

    To avoid triggering this, any modification of the expression on the lhs will do:

    df %>%
      mutate(name = str_to_lower(name)) %>%
      bind_rows((.) %>% mutate(name = "New England"))
    
    df %>%
      mutate(name = str_to_lower(name)) %>%
      bind_rows({.} %>% mutate(name = "New England"))
    
    df %>%
      mutate(name = str_to_lower(name)) %>%
      bind_rows(identity(.) %>% mutate(name = "New England"))
    

    Here's a suggestion that avoid the problem altogether:

    df %>%
      # arbitrary piped operation
      mutate(name = str_to_lower(name)) %>%
      replicate(2,.,simplify = FALSE) %>%
      map_at(2,mutate_at,"name",~"New England") %>%
      bind_rows
    
    # # A tibble: 12 x 2
    #    name        estimate
    #    <chr>          <dbl>
    #  1 ct            501074
    #  2 ma           1057316
    #  3 me             47369
    #  4 nh             76630
    #  5 ri            141206
    #  6 vt             27464
    #  7 New England   501074
    #  8 New England  1057316
    #  9 New England    47369
    # 10 New England    76630
    # 11 New England   141206
    # 12 New England    27464
    
    0 讨论(0)
提交回复
热议问题