niszetの日記

細かい情報を載せていくブログ

(R) reprexパッケージでfile読み込む場合の注意点

ファイル読むときも{}で囲う必要がある

先日、Rスクリプトreprexパッケージを使って表示させようと思って実行してみたところ、

> reprex::reprex(input="igraph_test.R")

Rendering reprex...
Error: Functions that produce HTML output found in document targeting markdown_strict output.
Please change the output type of this document to HTML. Alternatively, you can allow
HTML output in non-HTML formats by adding this option to the YAML front-matter of
your rmarkdown file:

  always_allow_html: yes

Note however that the HTML output will not be visible in non-HTML formats.

In addition: Warning messages:
1: In readLines(path) : incomplete final line found on 'igraph_test.R'
2: In grepl("#+ reprex-setup", data$body, fixed = TRUE) :
  input string 1 is invalid in this locale

こんなエラーが。これに地味に時間を食われました。ので、メモ。

reprex::rexprex()で入力をファイルにする場合、その全体が{} で囲われている必要があります。実際に実行した結果にはコードも表示されるので、結果だけ書けば

{
library(igraph)
library(tidyverse)

df <- data.frame(from=c(1,2,2,2,3,3,4), 
                 to=c(2,1,3,4,2,4,3), 
                 weight=c(0.7,1.3,1.7,0.7,1.7,1.7,1.2))

g <- igraph::graph.data.frame(df)

igraph::shortest.paths(graph = g, mode="out")}
#> 
#>  次のパッケージを付け加えます: 'igraph'
#>  以下のオブジェクトは 'package:stats' からマスクされています: 
#> 
#>      decompose, spectrum
#>  以下のオブジェクトは 'package:base' からマスクされています: 
#> 
#>      union
#>     1   2   3   4
#> 1 0.0 0.7 2.4 1.4
#> 2 1.3 0.0 1.7 0.7
#> 3 3.0 1.7 0.0 1.7
#> 4 4.2 2.9 1.2 0.0

Created on 2018-07-28 by the reprex package (v0.2.0).

みたいになるわけです。気を付けよう。

また、これはファイルを入力する場合に限らないですが、画像はuploadされてしまいます。
先のコードにplot(g)と入れると、下記のファイルへのリンクが出力されます。

https://i.imgur.com/5C6PtcX.png%29

なので、外に出してはいけないデータでreprex()するのは控えたほうが良いですね。問題を再現できる最低限のコードと疑似データで実行する必要があるということですね。こちらも気を付けよう。

Enjoy!!