全部版块 我的主页
论坛 计量经济学与统计论坛 五区 计量经济学与统计软件 LATEX论坛
1688 4
2016-06-18
Fast-track publishing using the new R markdown – a tutorial and a quick look behind the scenesby MAX GORDON posted on JULY 29, 2014
THE NEW RMARKDOWN REVOLUTION HAS STARTED. THE IMAGE IS CC BY JONATHAN COHEN.

The new R Markdown (rmarkdown-package) introduced in Rstudio 0.98.978 provides some neat features by combining the awesome knitr-package and the pandoc-system. The system allows for some neat simplifications of the fast-track-publishing (ftp) idea using so calledformats. I’ve created a new package, the Grmd-package, with an extension to thehtml_document format, called the docx_document. The formatter allows an almost pain-free preparing of MS Word compatible web-pages.

In this post I’ll (1) give a tutorial on how to use the docx_document, (2) go behind the scenes of the new rmarkdown-package and RStudio ≥ 0.98.978, (3) show what problems currently exists when skipping some of the steps outlined in the tutorial.

tutorial on how to use ftp with the rmarkdown implementation

A major improvement in the new rmarkdown is the YAML set-up. It is now much easier to set-up environments for your documents, all you need to look at is the function arguments in the documentation and provide those in the file. You have four different default document types where some options shared while other are output-specific: html_document, pdf_document,word_document, or markdown_document.

As mentioned above, the Grmd-package also contains a formatter, the docx_documentformat that is a wrapper around the html_document. It has the same options as thehtml_document with a few additions/defaults adapted to the concept of fast-track-publishing. As the package depends on rmarkdown it can currently only installed from Github (CRAN does not allow dependencies on packages outside CRAN) and in order to install the package you need to use the devtools-package:

?[url=]View Code[/url] RSPLUS

1234# If you don't have devtools install run below line:install("devtools")# Then install the Grmd-package by running below code:devtools::install_github("gforge/Grmd")

After this you simply put at the top of your Rmd-document:

?[url=]View Code[/url] RSPLUS

123---output: Grmd::docx_document---

If you may notice that after adding the above change from html_document to the customGmisc::docx_document-format the choice knit-box intelligently changes from:

to:

As RStudio is uncertain of how to approach this new format. Note: interestingly this also occurs if you happen to set the rstudio.mardownToHTML option using options().

For this tutorial we will use the Rmd document found in the Github ftp-repository. It is a simple example using my two main packages.



二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2016-6-18 20:34:05
?[url=]View Code[/url] RMARKDOWN

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113---title: "A fast-track-publishing demo"output:   Grmd::docx_document:    fig_caption: TRUE    force_captions: TRUE--- End section of methods====================== ```{r Data_prep, echo=FALSE, message=FALSE, warning=FALSE}# Moved this outside the document for easy of reading# I often have those sections in heresource("Setup_and_munge.R")``` ```{r Versions}info <- sessionInfo()r_ver <- paste(info$R.version$major, info$R.version$minor, sep=".")``` All analyses were performed using R (ver. `r r_ver`)[R Core Team, 2013] and packages rms (ver. `r info$otherPkgs$rms$Version`) [F. Harrell, 2014] for analysis, Gmisc for plot and table output (ver. `r info$otherPkgs$Gmisc$Version`), and knitr (ver `r info$otherPkgs$knitr$Version`) [Xie, 2013] for reproducible research. Results======= We found `r nrow(melanoma)` patients with malignant melanoma between the years `r paste(range(melanoma$year), collapse=" and ")`. Patients were followed until the end of 1977, the median follow-up time was `r sprintf("%.1f", median(melanoma$time_years))` years (range `r paste(sprintf("%.1f", range(melanoma$time_years)), collapse=" to ")` years). Males were more common than females and had also a higher mortality rate. ```{r Table1, cache=FALSE}table_data <- list()getT1Stat <- function(varname, digits=0){  getDescriptionStatsBy(melanoma[, varname], melanoma$status,                         add_total_col=TRUE,                        show_all_values=TRUE,                         hrzl_prop=TRUE,                        statistics=FALSE,                         html=TRUE,                         digits=digits)} # Get the basic statstable_data[["Sex"]] <- getT1Stat("sex")table_data[["Age<sup>&dagger;</sup>"]] <- getT1Stat("age")table_data[["Ulceration"]] <- getT1Stat("ulcer")table_data[["Thickness<sup>&Dagger;</sup>"]] <- getT1Stat("thickness", digits=1) mergeDesc(table_data) %>%  htmlTable(header = gsub("[ ]*death", "", colnames(table_data[[1]])),            # Add a column spanner            cgroup = c("", "Death"),            n.cgroup = c(2, 2),            caption="Baseline characteristics",             tfoot="<sup>&dagger;</sup> Age at the time of surgery.            <sup>&Dagger;</sup> Tumour thickness, also known as Breslow thickness, measured in mm.",            align="rrrr",            css.rgroup = "") ``` Main results------------ ```{r C_and_A, results='asis'}label(melanoma$sex) <- "Sex"label(melanoma$age) <- "Age"label(melanoma$ulcer) <- "Ulceration"label(melanoma$thickness) <- "Breslow thickness" # Setup needed for the rms coxph wrapperddist <- datadist(melanoma)options(datadist = "ddist") # Do the cox regression model # for melanoma specific deathmsurv <- Surv(melanoma$time_years, melanoma$status=="Melanoma death")fit <- cph(msurv ~ sex + age + ulcer + thickness, data=melanoma) # Print the modelprintCrudeAndAdjustedModel(fit,                            desc_digits=0,                           caption="Adjusted and unadjusted estimates for melanoma specific death.",                           desc_column=TRUE,                           add_references=TRUE,                            ctable=TRUE) pvalues <-   1 - pchisq(coef(fit)^2/diag(vcov(fit)), df=1)``` After adjusting for the three variables, age, sex, tumor thickness and ulceration, only the latter two remained significant (p-value `r txtPval(pvalues["ulcer=Present"], lim.sig=10^-3)` and `r txtPval(pvalues["thickness"], lim.sig=10^-3)`), see table `r as.numeric(options("table_counter"))-1` and Fig. `r figCapNoNext()`. ```{r Regression_forestplot, fig.height=3, fig.width=5, out.height=300, out.width=500, dpi=300, fig.cap=figCapNo("A forest plot comparing the regression coefficients.")}# The output size can be fixed by out.width=625, out.height=375 but you loose the caption# I've adjusted the coefficient for age to be by forestplotRegrObj(update(fit, .~.-age+I(age/10)),                   order.regexps=c("Female", "age", "ulc", "thi"),                  box.default.size=.25, xlog=TRUE, zero=1,                  new_page=TRUE, clip=c(.5, 6), rowname.fn=function(x){  if (grepl("Female", x))    return("Female")   if (grepl("Present", x))    return("Ulceration")   if (grepl("age", x))    return("Age/10 years")   return(capitalize(x))})``` ```

with the accompanying setup_and_munge.R script:

?[url=]View Code[/url] RSPLUS

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566################### Knitr settings ################### knitr::opts_chunk$set(warning=FALSE,                      message=FALSE,                      echo=FALSE,                      dpi=96,                      fig.width=4, fig.height=4, # Default figure widths                      dev="png", dev.args=list(type="cairo"), # The png device                      # Change to dev="postscript" if you want the EPS-files                      # for submitting. Also remove the dev.args() as the postscript                      # doesn't accept the type="cairo" argument.                      error=FALSE) # Evaluate the figure caption after the plotknitr::opts_knit$set(eval.after='fig.cap') # Use the table counter that the htmlTable() providesoptions(table_counter = TRUE) # Use the figCapNo() with roman lettersoptions(fig_caption_no_roman = TRUE) ################## Load_packages ##################library(rms) # I use the cox regression from this packagelibrary(boot) # The melanoma data set is used in this exampelibrary(Gmisc) # Stuff I find convenientlibrary(Greg) # You need to get this from my GitHub see http://gforge.se/Gmisclibrary(magrittr) # The excellent piping package ################### Munge the data ################### # Here we go through and setup the variables so that# they are in the proper format for the actual output # Load the dataset - usually you would use read.csv# or something similardata("melanoma") # Set time to years instead of daysmelanoma$time_years <-  melanoma$time / 365.25 # Factor the basic variables that# we're interested inmelanoma$status <-  factor(melanoma$status,         levels=c(2, 1, 3),         labels=c("Alive", # Reference                  "Melanoma death",                  "Non-melanoma death"))melanoma$sex <-  factor(melanoma$sex,         labels=c("Male", # Reference                  "Female")) melanoma$ulcer <-  factor(melanoma$ulcer,         levels=0:1,         labels=c("Absent", # Reference                  "Present"))

Will provide the following browser output:

copy-paste directly from browser

Copy-pasting directly from the web-browser works! The current compatibility that I’ve checked are (Windows 8.1):

  • RStudio viewer ≤ 0.98.978: works for headers, text, and tables but not for images.
  • Internet explorer ≥ v.11: works for all (headers, text, tables, and images).
  • Chrome ≥ v.36: works for all (headers, text, tables, and images).
  • Firefox ≤ v.31: works for no elements.

二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2016-6-18 20:34:59
发了不少 R markdown 的帖子,辛苦了。
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2016-6-18 20:37:37
谢谢分享
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2016-6-19 05:33:09
oliyiyi 发表于 2016-6-18 20:17
Fast-track publishing using the new R markdown – a tutorial and a quick look behind the scenesby MA ...
谢谢分享
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群