Unloading package in one block does not affect the next block



I have been chasing an odd behaviour in a chapter of a bookdown book. The book used to build fine but suddenly I started getting an error at my select statement in a dplyr pipe chain: error in select... unused arguments... Well I know that error. We're old friends. That's what I get if I use select from dplyr with the MASS package loaded. I have no idea why MASS is loaded at that point in the book, but I'm pragmatic so just trying to build the dang thing. So I add a code block to unload MASS:

detach("package:MASS", unload=TRUE)

and I was shocked to discover I kept getting the same error. So I set up a little test case to see if unloading in the same code block matters. And it DID... but it shouldn't (I don't believe). And then after unloading, in the next cell block MASS is back like a bad penny!:

Here's the test I set up right in the middle of my book chapter. I'm doing screen shot because I can't get the tics to show right in this forum:

The output below shows that when I unload MASS in its own code block, the package is still very much loaded in the next code block. However if I unload in the same code block, then it's unloaded for that code block. But in the following code block it's back!!


Oddly enough, when I try to reprex this in a single page R Markdown document the behavior is as expected. It's only in my book where the behavior is borked. I have reproduced this on my Macbook Pro as well as Rstudio.server Linux. Here's the rstudio.server session info:

> sessionInfo()
R version 3.4.4 (2018-03-15)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.4 LTS

Matrix products: default
BLAS: /usr/lib/atlas-base/atlas/libblas.so.3.0
LAPACK: /usr/lib/atlas-base/atlas/liblapack.so.3.0

 [1] LC_CTYPE=C.UTF-8       LC_NUMERIC=C           LC_TIME=C.UTF-8        LC_COLLATE=C.UTF-8    
 [5] LC_MONETARY=C.UTF-8    LC_MESSAGES=C.UTF-8    LC_PAPER=C.UTF-8       LC_NAME=C             

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

other attached packages:
[1] bookdown_0.7

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.17     knitr_1.20       bindr_0.1.1      magrittr_1.5     tidyselect_0.2.4 munsell_0.4.3   
 [7] colorspace_1.3-2 R6_2.2.2         rlang_0.2.0      stringr_1.3.1    plyr_1.8.4       dplyr_0.7.5     
[13] tools_3.4.4      grid_3.4.4       gtable_0.2.0     xfun_0.1         htmltools_0.3.6  yaml_2.1.19     
[19] lazyeval_0.2.1   assertthat_0.2.0 digest_0.6.15    rprojroot_1.3-2  tibble_1.4.2     bindrcpp_0.2.2  
[25] purrr_0.2.4      ggplot2_3.0.0    glue_1.2.0       evaluate_0.10.1  rmarkdown_1.9    stringi_1.2.2   
[31] compiler_3.4.4   pillar_1.2.2     scales_0.5.0     backports_1.1.2  pkgconfig_2.0.1 

Any ideas on how to go about debugging this? I'm struggling to imagine what might even cause something like this.