Meaning of error using . shorthand inside dplyr function

青春壹個敷衍的年華 提交于 2019-11-29 11:14:27

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!