r mah_knitr.R

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了r mah_knitr.R相关的知识,希望对你有一定的参考价值。

library(yaml)
library(tools)
library(dplyr)
library(tidyr)

library(ggplot2)
library(RColorBrewer)
library(gridExtra)
library(extrafont)
#setwd(rstudioapi::getActiveProject())

library(utils)
ed <- function(...) {
  file.edit(...)
}

# library
suppressMessages(library(dplyr))
library(tidyr)
library(ggplot2)
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
  library(grid)
  
  # Make a list from the ... arguments and plotlist
  plots <- c(list(...), plotlist)
  
  numPlots = length(plots)
  
  # If layout is NULL, then use 'cols' to determine layout
  if (is.null(layout)) {
    # Make the panel
    # ncol: Number of columns of plots
    # nrow: Number of rows needed, calculated from # of cols
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                     ncol = cols, nrow = ceiling(numPlots/cols))
  }
  
  if (numPlots==1) {
    print(plots[[1]])
    
  } else {
    # Set up the page
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
    
    # Make each plot, in the correct location
    for (i in 1:numPlots) {
      # Get the i,j matrix positions of the regions that contain this subplot
      matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
      
      print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                      layout.pos.col = matchidx$col))
    }
  }
}

# packages install
brew <- function(){
  brew_install <- function(pkg){
    new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
    if (length(new.pkg)) 
      install.packages(new.pkg, dependencies = TRUE, repos='http://cran.rstudio.com/')
    # sapply(pkg, require, character.only = TRUE)
  }
  packages <- c(
    # "ggpmisc", "ggsci", "ggspectra", "ggthemes", "ggTimeSeries",
    #             "ggrepel","extrafont", "gcookbook",
    #             'RColorBrewer',
    #             "googleVis","googleCharts",
    # "ncdf4",
    # "extrafont",
    "gsheet","rstudioapi",
    "ggpmisc","gridExtra","ggthemes",
    # "rattle",
    # "rgdal",
    "rticles")
  brew_install(packages)
  
  # , "raster"
  
  # install.packages('rgdal', type = "source", configure.args=c(
  #   '--with-gdal-config=/Library/Frameworks/GDAL.framework/Programs/gdal-config',
  #   '--with-proj-include=/Library/Frameworks/PROJ.framework/Headers',
  #   '--with-proj-lib=/Library/Frameworks/PROJ.framework/unix/lib'))
  # 
  # install.packages('raster', type = "source", configure.args=c(
  #   '--with-gdal-config=/Library/Frameworks/GDAL.framework/Programs/gdal-config',
  #   '--with-proj-include=/Library/Frameworks/PROJ.framework/Headers',
  #   '--with-proj-lib=/Library/Frameworks/PROJ.framework/unix/lib'))
}

# Rmarkdown enhance
library(knitr)
opts_chunk$set(echo = T, message = T, warning = T)
knit_hooks$set(
  par = function(before, options, envir) {
    id = options$label
    isfig = startsWith(id, 'fg')
    istbl = startsWith(id, 'tb')
    print(isfig)
    pdfname = sprintf('graph/%s.pdf', id)
    jpgname = sprintf('graph/%s.jpeg', id)
    pngname = sprintf('graph/%s.png', id)
    ispdf = file.exists(pdfname)
    isjpg = file.exists(jpgname)
    if (before) { # start to parse
      if (istbl) {# tables.pdf
        return(
          paste(
            '\\begin{table}',
            sprintf('\\captionsetup{justification=centering}\\caption{%s}', options$ti),
            sprintf('\\label{%s}', id),
            sprintf( '\\includegraphics[scale=%s,trim={%scm},clip]{%s}', options$scale, gsub(' ', 'cm ', options$trim), pdfname),
            '\\end{table}',
            sep = '\n'
          )
        )
      } else {
        # if (isjpg) fname = jpgname else fname = pngname
        # if (ispdf) fname = pdfname else fname = jpgname
        fname = ifelse(ispdf, pdfname, ifelse(isjpg, jpgname, pngname))
        return(
          paste(
            '',
            '\\begin{figure}[H]',
            '  \\centering',
            sprintf( '  \\includegraphics[width=\\textwidth,height=\\textheight,keepaspectratio]{%s}', fname),
            sprintf('  \\caption{%s}', options$ti),
            sprintf('  \\label{%s}', id),
            '\\end{figure}',
            sep = '\n'
          )
        )
      }
    }
  }
)
knit_hooks$set(
  endix = function(before, options, envir) {
    if (before) {
      return(
        paste(
          '\\newpage',
          '\\phantomsection \\label{listoffig}',
          '\\addcontentsline{toc}{section}{List of Figures}',
          '\\listoffigures',
          '',
          '\\newpage',
          '\\phantomsection \\label{listoftbl}',
          '\\addcontentsline{toc}{section}{List of Tables}',
          '\\listoftables',
          '',
          '# Reference {#references .unnumbered}',
          '\\setlength{\\parindent}{-0.5in}',
          '\\setlength{\\leftskip}{0.5in}',
          '\\setlength{\\parskip}{8pt}',
          sep = '\n'
        )
      )
    }
  }
)

以上是关于r mah_knitr.R的主要内容,如果未能解决你的问题,请参考以下文章

——R的数据组织

+-r, +-s 的所有排列

shinydashboard ui.R 和 server.R 未读取 Global.R

R语言计算回归模型R方(R-Squared)实战

r语言中r-studio怎么调用

R电子书资料《学习R》+《R语言实战第2版》+《R数据科学》学习推荐