メモ:knitrのoutput hookを使ってパスを隠す

実行結果にパスが含まれる系のやつ、なんか恥ずかしいので隠したい///と思うことがたまーにありますよね。 そんなときはknitrのhookです。

output hookには8種類ありますが、必要に応じて使い分けましょう(書き換えようとしている出力がメッセージか、警告か、それ以外の出力か、など)。 具体的にはこんな感じ。

---
output: github_document
---

 ```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

orig_hook <- knitr::knit_hooks$get("output")

knitr::knit_hooks$set(
  output = function(x, options) {
    x <- orig_hook(x, options)
    ptn <- normalizePath(Sys.getenv("HOME"))
    gsub(ptn, "C:\\path\\to", x, fixed = TRUE)
  }
)
 ```

 ```{r}
library(sf)
 
nc <- st_read(system.file("shape/nc.shp", package="sf"))
 ```

結果はこうなる:

 ``` r
library(sf)
 ```

    ## Linking to GEOS 3.6.1, GDAL 2.2.3, proj.4 4.9.3

 ``` r
nc <- st_read(system.file("shape/nc.shp", package="sf"))
 ```

    ## Reading layer `nc' from data source `C:\path\to\R\win-library\3.5\sf\shape\nc.shp' using driver `ESRI Shapefile'
    ## Simple feature collection with 100 features and 14 fields
    ## geometry type:  MULTIPOLYGON
    ## dimension:      XY
    ## bbox:           xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
    ## epsg (SRID):    4267
    ## proj4string:    +proj=longlat +datum=NAD27 +no_defs