It is written after reading Efficient R programming book website.(https://csgillespie.github.io/efficientR/)


1. Prerequisites

library("microbenchmark")
library("profvis")
library("ggplot2")

#install 3 packages and attach by using install.packages() and library()


2. profiling

profvis( expr = { any code })

# this code can show you how long each code takes and how much each code takes by percent


3. system and Ram

Sys.info()

#see your OS and its version etc.


# Note: uses 2+ GB RAM and several seconds or more depending on hardware

# 1: Create large dataset

X = as.data.frame(matrix(rnorm(1e8), nrow = 1e7))

# 2: Find the median of each column using a single core

r1 = lapply(X, median)

# 3: Find the median of each column using many cores

r2 = parallel::mclapply(X, median)

#mclapply only work in parallel on Mac or Linux. we must use parLapply() on Windows.


4. packages

install.packages('installr')

installr::updateR()

#if R return FALSE, your Rversion is uptodate.


pkgs = c('raster', 'leaflet', 'rgeos')

install.packages(pkgs)

inst = lapply(pkgs, library, characher.only = TRUE)

#to shorten code, install packages in only two line of code and use lapply

#to make library(pkgs[i]).

#we use library instead of require because the former returns error when pkg is not installed.


update.packages()

#default of ask parameter is TRUE, change it to FASLE if you want.

#if you want this code run automatically when starting R

#you can add update.packages(ask = FALSE) in .Rprofile startup file


5. .Rprofile

# A fun welcome message
message("Hi your name, Welcome")

#print fortune message when R starts
if(interactive()) 
  try(fortunes::fortune(), silent = TRUE)

# `local` creates a new, empty environment
# This avoids polluting .GlobalEnv with the object r
local({
  r = getOption("repos")             
  r["CRAN"] = "https://cran.rstudio.com/"
  options(repos = r)
})

#nice par for nice plotting
nice_par = function(mar = c(3, 3, 2, 1), mgp = c(2, 0.4, 0), tck = -0.01, 
                    cex.axis = 0.9, las = 1, mfrow = c(1, 1), ...) {
  par(mar = mar, mgp = mgp, tck = tck, cex.axis = cex.axis, las = las, 
      mfrow = mfrow, ...)
}

#.env makes hidden environment
.env = new.env()
#head and tail function
.env$ht = function(d, n = 5) rbind(head(d, n), tail(d, n))
attach(.env)

#.Last will work when R session ended.
.Last = function() {
  cond = suppressWarnings(!require(fortunes, quietly = TRUE))
  if(cond) 
    try(install.packages("fortunes"), silent = TRUE)
  message("Goodbye at ", date(), "\n")
}


'Programming' 카테고리의 다른 글

가상환경을 위해 WSL(windows subsystem for Linux) 깔아보기  (0) 2020.05.06
html, css 가운데 정렬 총 정리  (0) 2020.04.11
[R] ggplot error message  (0) 2018.12.06
[R] ggplot basic item  (0) 2018.12.06
[R] ggplot coloring manual  (0) 2018.12.06

+ Recent posts