加载了dplyr的函数找不到“%<>%”

时间:2019-03-27 15:47:05

标签: r dplyr pipe

[免责声明:类似的问题已经问了很多遍了。我不认为这与我刚刚阅读的许多线程相同。]

我做到了:

library(dplyr)
colnames(LarvalSamples) %<>% 
  stringr::str_remove_all("_log") %>% 
  stringr::str_replace_all("Sea_Level", "Sea_Level_Height") %>% #sealevel, sealion, chinook, chl
  stringr::str_replace_all("SeaLion", "Sea_lion") %>% 
  stringr::str_replace_all("Chinook_Salmon", "Salmon") %>% 
  stringr::str_replace_all("Chlorophyll_a", "Chlorophyll_A")

工作正常,没有消息,按预期/期望输出。然后我复制/粘贴了前两行,除了终端管道:

colnames(LarvalSamples) %<>%
  stringr::str_remove_all("_log")
  

colnames(LarvalSamples)中的错误%<>%stringr :: str_remove_all(“ _ log”)   :找不到函数“%<>%”

我意识到这里还有其他关于找不到函数的文章,但是dplyr已被加载并在上面的两行中处理了更多代码。碰巧的是,"_log"中没有colnames模式,但我尝试了一个确实存在的字符模式,但失败了,因此消除了一个潜在的错误源。任何想法/猜测都表示赞赏,这比问题tbh更像是一个错误,但如果需要的话,在将其提升到整个链之前,最好能有敏锐的目光。谢谢。

> sessionInfo()
R version 3.5.0 (2018-04-23)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17134)

Matrix products: default

locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252   
[3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C                           
[5] LC_TIME=English_United Kingdom.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] dplyr_0.8.0.1  beepr_1.3      gbm.auto_1.2.0

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.0       compiler_3.5.0   pillar_1.3.1     shapefiles_0.7   tools_3.5.0      tibble_2.0.1    
 [7] gtable_0.2.0     lattice_0.20-35  pkgconfig_2.0.2  rlang_0.3.1      Matrix_1.2-14    DBI_1.0.0       
[13] rstudioapi_0.9.0 rgdal_1.4-2      gbm_2.1.5        dismo_1.1-4      gridExtra_2.3    stringr_1.4.0   
[19] raster_2.8-19    mapplots_1.5.1   rgeos_0.4-2      grid_3.5.0       tidyselect_0.2.5 glue_1.3.0      
[25] R6_2.4.0         survival_2.41-3  foreign_0.8-70   sp_1.3-1         purrr_0.3.1      magrittr_1.5    
[31] codetools_0.2-15 splines_3.5.0    maptools_0.9-5   assertthat_0.2.0 stringi_1.3.1    crayon_1.3.4    
[37] audio_0.1-5.1  

更新:以下可复制的示例。这肯定是一个错误。有了全新的系统:

Data <- data.frame(
    Name_Bad = sample(1:10),
    Name_Guud = sample(1:10)
  )

  colnames(Data) %<>%
    stringr::str_remove_all("_Bad") %>%
    stringr::str_replace_all("Guud", "Good")
  # Error: could not find function "%>%"

  install.packages("dplyr")
  library(dplyr)
  install.packages("stringr")
  library(stringr)

  colnames(Data) %<>%
    stringr::str_remove_all("_Bad") %>%
    stringr::str_replace_all("Guud", "Good")
# no error, worked

  colnames(Data) %<>%
    stringr::str_remove_all("_Bad")
  # Error: could not find function "%<>%"

1 个答案:

答案 0 :(得分:5)

dplyr不会导出

%<>%(仅%>%)。您需要加载magrittr。

您的可复制示例遇到了a subtle magrittr bug,这导致对管道表达式的求值在magrittr的范围内而不是在调用范围内搜索某些运算符。这样,x %<>% y %>% z的评估结果为`%>%`(x %<>% y, z),可以找到并评估magrittr的`%<>%`运算符。