问题描述
遵循?across
的文档:
across(.cols = everything(),.fns = NULL,...,.names = NULL)
我使用everything()
作为LHS的参考。
everything()
和.
似乎都没有从管道接收LHS对象。
我想念什么?
Repex:
library(dplyr)
# this works as expected
iris %>%
select(Sepal.Length:Petal.Width) %>%
mutate_all(as.character) %>% glimpse
Rows: 150
Columns: 2
$ Sepal.Length <chr> "5.1","4.9","4.7","4.6","5","5.4","5…
$ Sepal.Width <chr> "3.5","3","3.2","3.1","3.6","3.9","3.4","3…
# this doesn't work
iris %>%
select(Sepal.Length:Sepal.Width) %>%
mutate(across(.cols = everything(),.fns = as.character)) %>% glimpse
Rows: 150
Columns: 2
$ Sepal.Length <dbl> 5.1,4.9,4.7,4.6,5.0,5.4,4.4,…
$ Sepal.Width <dbl> 3.5,3.0,3.2,3.1,3.6,3.9,3.4,2.9,…
解决方法
经过繁琐的试验和错误后,我找到了解决方案。 我发布该邮件是因为我认为它并不简单,尤其是对于dplyr的初学者。
发生此问题的原因是dplyr库调用中的mutate
可能被plyr
库覆盖。棘手的方面是,后者库是作为其他库的依赖项加载的。在这种情况下,您需要在加载库后仔细阅读警告消息。
在我的情况下,plyr
由ggbiplot
加载:
library(ggbiplot)
Loading required package: plyr
-----------------------------------------------------------------------
You have loaded plyr after dplyr - this is likely to cause problems.
If you need functions from both plyr and dplyr,please load plyr first,then dplyr:
library(plyr); library(dplyr)
-----------------------------------------------------------------------
重要的是,警告消息明确命名了那些被覆盖的dplyr函数:
Attaching package: ‘plyr’
The following objects are masked from ‘package:dplyr’:
arrange,count,desc,failwith,id,mutate,rename,summarise,summarize
在这种情况下,修复很容易:
library(plyr)
library(dplyr)
library(ggiplot)
我认为最安全的方法是确保从dplyr调用每个dplyr函数:
iris %>%
dplyr::select(Sepal.Length:Sepal.Width) %>%
dplyr::mutate(across(.cols = everything(),.fns = as.character)) %>% glimpse