R Markdown Websites :: 정적인 웹사이트

Published by onesixx on

정적인 웹사이트 -> Dashboard -> Shiny

 

http://rmarkdown.rstudio.com/rmarkdown_websites.html

정적인 웹사이트 구조

  • _site.yml
  • index.Rmd
  • _output.yml

R Markdown Websites

Overview

rmarkdown::render_site함수를 사용하여 R markdown문서들을 website로 만들수 있다. 

install.packages("rmarkdown")

Simple Example

Home, About 페이지와  navigation bar 가 있는 간단한 웹페이지 
https://github.com/rstudio/rmarkdown-website-examples/tree/master/hello-website.

필요 파일

사이트 구성을 위해서는 일단 두개의 파일이 필요하다. ( _site.yml과 index.Rmd )

_site.yml

name: "my-website"
navbar:
  title: "My Website"
  left:
    - text: "Home"
      href: index.html
    - text: "About"
      href: about.html

index.Rmd

---
title: "My Website"
---

Hello, Website!

 

Build

Build (rmarkdown::render_site함수 실행) 하면, 
1.  모든 Rmd와 md 파일은 Html로 렌더링된다. ( “_”로 시작하는 파일은 제외)
2.  output 폴더에 생성된 Html파일과 지원파일(css, javascript등…)이 복사된다. 

결과:

추가 파일

_output.yml

.Rmd파일이 .Html파일로 렌더링되는 방법을 정의.
_site.yml파일에 output: 항목으로 추가해도 되지만 깔끔하게 분리하는게 내 스타일~

html_document:
    theme: united
    toc: yes

about.Rmd : 페이지 추가
….

---
title: "About This Website"
---

More about this website.

 

 

Site Authoring

 

RStudio

RStudio includes a variety of features intended to make developing R Markdown websites more productive. These features are available in version 1.0 or higher of RStudio so you should be sure to update RStudio prior to using R Markdown websites. You can download the latest version of RStudio here: https://www.rstudio.com/products/rstudio/download/.

Website Project

Note that all of the RStudio features for website authoring described below require the use of an RStudio Project tied to your website’s directory. See the documentation on RStudio Projects for additional information on how to create and use projects.

Individual Pages

As you work on the individual pages of your website you can render them using the Knit button just as you do with conventional standalone R Markdown documents:

Knitting an individual page will only render and preview that page, not the other pages in the website.

Entire Website

To render all of the pages in the website you use the Build pane, which calls rmarkdown::render_site to build and then preview the entire site:

Supporting Files

RStudio supports “live preview” of changes that you make to supporting files within your website (e.g. CSS, JavaScript, Rmd partials, R scripts, YAML config files, etc.).

Changes to CSS and JavaScript files always result in a refresh of the currently active page preview. Changes to other files (e.g. shared scripts and config files) trigger a re-knit of the active page preview (this behavior can be disabled via the options dialog available from the Build pane).

Note that only the active page is re-knit so once you are happy with the results of rendering you should be sure to rebuild the entire site from the Build pane to ensure that all pages inherit your changes.

Side by Side Preview

When working iteratively on a page you might find it more convenient to preview it side-by-side with the editor rather than in an external window. You can configure RStudio to do this using the options menu on the editor toolbar:

 

Command Line

Rendering

If you aren’t working within RStudio and/or want to build sites from the command line you can call the render_site function directly from within the website directory. Pass no arguments to render the entire site or a single file in order to render just that file:

# render the entire site
rmarkdown::render_site()

# render a single file only
rmarkdown::render_site("about.Rmd")

Cleaning Up

To clean up all of the files generated via render_site you can call the clean_site function, which will remove all files generated by rendering your site’s markdown documents including knitr _cache directories. You can specify the preview = FALSE option to just list the files to be removed rather than actually removing them:

# list which files will be removed
rmarkdown::clean_site(preview = TRUE)

# actually remove the files
rmarkdown::clean_site()

 

knitr Caching

If your website is time consuming to render you may want to enable knitr caching during the development of the site so that you can more rapidly preview changes. To enable caching for an individual chunk just add the cache = TRUE chunk option:

```{r, cache = TRUE}
data <- longComputation()
```

To enable caching for an entire document add cache = TRUE to the global chunk option defaults:

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

Note that when knitr caching is enabled for an Rmd it’s _files directory will be copied rather than moved to the _site directory (since the cache requires references to generated figures in the _files directory).

 

Common Elements

 

 

R Scripts

If you have R code that you’d like to share across multiple R Markdown documents within your site you can simply create an R script (e.g. “utils.R”) and then source it within your Rmd files. For example:

```{r}
source("utils.R")
```

 

Rmd Partials

You may have common fragments of R Markdown that you want to share across pages within your site. To share Rmd fragments you should name them with a leading underscore (_) then include them within their parent Rmd document using the child chunk option. For example:

about.Rmd

---
title: "About This Website"
---

More about this website.

```{r, child="_sessioninfo.Rmd"}
```

_sessioninfo.Rmd

Session information:

```{r}
sessionInfo()
```

The leading underscore is an indicator to the site generation engine that the Rmd is a partial document to be included in other documents so it’s not Knit as a standalone document during site rendering.

The full source code for the above example can be found here: https://github.com/rstudio/rmarkdown-website-examples/tree/master/common-elements

 

Site Navigation

The navbar element of _site.yml can be used to define a common navigation bar for your website. You can include internal and external links on the navigation bar as well as drop-down menus for sites with a large number of pages.

Here’s a navigation bar definition that makes use of a variety of features:

_site.yml

name: "my-website"
navbar:
  title: "My Website"
  type: inverse
  left:
    - text: "Home"
      icon: fa-home
      href: index.html
    - text: "About"
      icon: fa-info
      href: about.html
    - text: "More"
      icon: fa-gear
      menu:
        - text: "Heading 1"
        - text: "Page A"
          href: page_a.html
        - text: "Page B"
          href: page_b.html
        - text: "---------"
        - text: "Heading 2"
        - text: "Page C"
          href: page_c.html
        - text: "Page D"
          href: page_d.html
  right:
    - icon: fa-question fa-lg
      href: https://example.com

This example demonstrates a number of capabilities of navigation bars:

  1. You can use the type field to choose between the “default” and “inverse” navigation bar style (each theme includes distinct colors for “default” and “inverse” navigation bars).

  2. You can align navigational items either to the left or to the right.

  3. You can include menus on the navigation bar, and those menus can have separators (text: “————–“) and internal headings (text without a corresponding href).

  4. You can include both internal and external links on the navigation bar.

  5. You can use icons on the navigation bar. Icons from three different icon sets are available.

    When referring to an icon you should use it’s full name including the icon set prefix (e.g. “fa-github”, “ion-social-twitter”, “glyphicon-time”, etc.).

HTML Navigation Bar

If you want to have even more control over the appearance and behavior of the navigation bar you can define it in HTML rather than YAML. If you include a file named _navbar.html in your website directory it will be used as the navigation bar. Here’s an example of navigation bar defined in HTML: https://github.com/rstudio/rmarkdown-website/blob/master/_navbar.html.

Full documentation on syntax of Bootstrap navigation bars can be found here: http://getbootstrap.com/components/#navbar.

 

HTML Generation

R Markdown includes many facilities for generation of HTML content from R objects, including:

  • The conversion to HTML of standard R output types (e.g. textual output, plots, etc.) within code chunks done automatically by knitr.

  • A variety of ways to generate HTML tables, including the knitr::kable function and the xtable package.

  • A large number of available HTML widgets that provide rich JavaScript data visualizations.

As a result, for many R Markdown websites you won’t need to worry about generating HTML output at all (since it’s created automatically).

htmltools Package

If the facilities described above don’t meet your requirements, you can also generate custom HTML from your R code using the htmltools package. The htmltools package enables you to write HTML using a convenient R based syntax (this is the same core HTML generation facility used by the shiny package).

Here’s an example of an R function that creates a Bootstrap thumbnail div:

library(htmltools)
thumbnail <- function(title, img, href, caption = TRUE) {
  div(class = "col-sm-4",
      a(class = "thumbnail", title = title, href = href,
        img(src = img),
        div(class = ifelse(caption, "caption", ""),
          ifelse(caption, title, "")
        )
      )
  )
}

You can write functions which build HTML like the one above then call them from other R code which combines them with your data to produce dynamic HTML. An R code chunk that makes use of this function might look like this:

```{r, echo=FALSE}
thumbnail("Apple", "images/apple.png", "https://en.wikipedia.org/wiki/Apple")
thumbnail("Grape", "images/grape.png", "https://en.wikipedia.org/wiki/Grape")
thumbnail("Peach", "images/peach.png", "https://en.wikipedia.org/wiki/Peach")
```

 

Site Configuration

The _site.yml file has a number of options that affect site output including where it is written and what files are included and excluded from the site. Here’s an example that makes use of a few of these options:

name: "my-website"
output_dir: "_site"
include: ["import.R"]
exclude: ["docs.txt", "*.csv"]

The name field provides a suggested URL path for your website when it is published (by default this is just the name of the directory containing the site).

The output_dir field indicates which directory to copy site content into (“_site” is the default if none is specified). Note that this can be “.” to keep all content within the root website directory alongside the source code.

Included Files

The include and exclude fields enable you to override the default behavior visa-vi what files are copied into the output directory. By default, all files within the website directory are copied into the output directory (e.g. “_site“) save for the following:

  1. Files beginning with “.” (hidden files).

  2. Files beginning with “_”

  3. Files known to contain R source code (e.g. “.R”, “.s”, “.Rmd”), R data (e.g. “.RData”, “.rds”), or configuration data (e.g. “.Rproj”, “rsconnect”)).

The include and exclude fields of _site.yml can be used to override this default behavior (wildcards can be used to specify groups of files to be included or excluded).

Note that include and exclude are not used to determine which Rmd files are rendered (all of them in the root directory save for those named with the _prefix will be rendered).

 

Publishing Websites

R Markdown websites are static HTML sites that can be deployed to any standard web server. All site content (generated documents and supporting files) are copied into the _site directory so deployment is simply a matter of moving that directory to the appropriate directory of a web server.

This section provides additional documentation on publishing websites to several popular hosting services.

GitHub Pages

R Markdown websites are can be hosted using GitHub Pages with two additions to the standard site configuration:

  1. Add a file named .nojekyll to your site source code directory (this tells GitHub Pages to not process your site with the Jekyll engine).

  2. Change your output directory to “.” within _site.yml. For example:

    output_dir: "."

This keeps all of your output side-by-side with your source code in the root of your website (rather than writing it to the _site directory).

Note that when deploying to GitHub Pages using this configuration your source code, data, and everything else in your repository is all publicly available alongside your generated website content.

Alternatively, you can configure GitHub Pages to publish from a /docs subdirectory of your repository. If you work in this configuration you should change your output directory to “docs” within _site.yml. For example:

    output_dir: "docs"
  

You can find an example of a minimal R Markdown website configured for publishing to GitHub Pages here: https://github.com/rstudio/rmarkdown-website-examples/tree/master/gh-pages.

Amazon S3

If you have an Amazon Web Services account, you can deploy your R Markdown website directly to the S3 storage service. S3-based websites have global replication, support custom domains, and can be accelerated via the use of the Amazon CloudFront CDN.

For additional information on deploying websites to S3 see: http://docs.aws.amazon.com/gettingstarted/latest/swh/website-hosting-intro.html.

Other Web Hosts

There are a wide variety of options for static web hosting, all of which are compatible with R Markdown websites. This guide includes an overview of several of the more popular services: http://alignedleft.com/resources/cheap-web-hosting.

 

Additional Examples

Here are some additional examples of websites created with R Markdown:

Site Description Source
rmarkdown This website was created using R Markdown. There are a large number of pages (over 40) that are organized using sub-menus on the navigation bar. Disqus comments are included on each page via an after_body include. View code
flexdashboard Documentation for the flexdashboard R package. Illustrates using an R script to dynamically generate HTML thumbnails of flexdashboard examples from YAML. View code
bookdown Home page for the bookdown R package and publishing service. Illustrates creating a site with a completely custom theme (no use of Bootstrap). View code
Categories: Presentation

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x