Вы находитесь на странице: 1из 27

R Prepare Peablog

CHAPTER 1: R STYLE GUIDE


Khi viết code, nhiều khi chúng ta không để ý đến các quy tắc viết code. Các đoạn code
trở nên lộn xộn, khó đọc. R style guide là một bộ các quy tắc do người viết code đặt
ra để viết code khoa học, dễ đọc hơn hay còn được gọi là phong cách lập trình. Trong
bài này mình chỉ note lại một số quy tắc theo chủ quan của mình. Dĩ nhiên mỗi người
sẽ có một phong cách viết code của riêng mình.

1. Quy tắc đặt tên


1.1. Tên file
Khi đặt tên file, mình sử dụng các ký tự viết thường, số và dấu gạch dưới. Tên file
không được bắt đầu bằng dấu gạch dưới.
Ví dụ đối với trường hợp các file riêng lẻ:
files_name.R

Ví dụ với trường hợp các file phải chạy theo một trình tự nào đó:
# More file -------------------------

01_file1_name.R
02_file2_name.R
...
10_file10_name.R

1.2. Tên biến và tên hàm


Tên biến và tên hàm, tương tự như đặt tên file. Khi đặt tên biến ta nên sử dụng các
danh từ, khi đặt tên hàm ta nên sử dụng các động từ.
>>> day_one
>>> bad_1

1.3. Têm đối số trong hàm


Khi đặt tên đối số trong hàm, ta có thể sử dụng các ký tự đơn, các từ đơn, nếu nhiều
từ thì dùng . để ngăn cách.
Ví dụ:
multiply = function(a, b) {
...
}

writeLinesToFile = function(file.path, lines, show.info = TRUE) {


...
}

Sometime I Write… 1
R Prepare Peablog

2. Syntax
2.1. Quy tắc về khoảng trắng
Khoảng trắng trước và sau các toán tử, sau dấu phảy:
# Khoảng trắng
average <- mean(feet / 12 + inches, na.rm = TRUE)

Khoảng trắng trước và sau condition trong mệnh đề for, if:


if (debug) show(x)
plot(x, y)
diamonds[5, ]

Không sử dụng khoảng trắng với dấu ngoặc () khi gọi hàm và với :, ::, !,…
x <- 1:10
base::get
list(
total = a + b + c,
mean = (a + b + c) / n
)

Thụt lề 2 khoảng trắng:


# Ngoặc kép và Thụt lề hai khoảng trắng
if (y < 0 && debug) {
message("y is negative")
}
if (y == 0) {
if (x > 0) {
log(x)
} else {
message("x is negative or zero")
}
} else {
y ^ x
}
test_that("call1 returns an ordered factor", {
expect_s3_class(call1(x, y), c("factor", "ordered"))
})

2.2. Ngắt mã
# Ngắt mã sau dấu phảy:
do_something_very_complicated(
"that",
requires = many,
arguments = "some of which may be long"
)

paste0(
"Requirement: ", requires, "\n",
"Result: ", result, "\n"
)

2 Sometime I Write…
R Prepare Peablog
2.3. Một số chú ý khác
# Sử dụng toán tử <- thay cho =

# Không sử dụng ; vào cuối dòng

# String:

"This is ..."
'Text with "quotes"'
'<a href="http://style.tidyverse.org">A link</a>'

# Sử dụng TRUE and FALSE thay T and F

# Sử dụng L phía sau số nguyên: Như 1L, 2L,...

# Viết 1:3 thay vì c(1:3)

3. Functions
# Định nghĩa hàm:
long_function_name <- function(a = "a long argument",
b = "another argument",
c = "another long argument") {
# As usual code is indented by two spaces.
}

# Sử dụng Return nếu cần trả về kết quả giữa đoạn, nếu k k sử dụng
find_abs <- function(x, y) {
if (x > 0) return(x)
x * -1
}
add_two <- function(x, y) {
x + y
}

# Các hàm print, plot, save sẽ trả về đối số đầu tiên

print.url <- function(x, ...) {


cat("Url: ", build_url(x), "\n", sep = "")
invisible(x)
}

# Một hàm chỉ nên làm một nhiệm vụ


# Một hàm chỉ nên gồm 20-30 dòng code, nếu dài hơn tách thành các hàm nhỏ

4. Toán tử Pipes
foo_foo %>%
hop(through = forest) %>%
scoop(up = field_mouse) %>%
bop(on = head)

iris %>% arrange(Petal.Width)

x %>%
unique() %>%
sort()

# sử dụng -> ở cuối pipes, không khuyến khích

Sometime I Write… 3
R Prepare Peablog

CHAPTER 2: MỘT SỐ THAO TÁC CƠ BẢN


1. Các thao tác với file trong R
# current working directory
getwd()

# files and folders in the current working directory


list.files()

# set the current working directory


setwd()

# Create new directory


dir.creat("path/dir_name")

# Tạo file
cat(file = "Example.R")

# Đưa nội dung vào một file:


cat("Reproducible Research with R and RStudio", file = "ExampleCat.md")

# Thêm nội dung vào một file


cat("More Text", file = "ExampleCat.md", append = TRUE)

# Xóa vĩnh viễn files and directories


unlink("path")

# Rename, move, copy:

file.rename(from = "path", to = "path")


file.copy(from = "path", to = "path")

2. Chạy R trong chế độ command lines


# Cú pháp:
Rscript [options] [-e expr [-e expr2 ...] | file] [args]

# Run Expression
Rscript -e ' 2 + 2 '
Rscript -e ' 2 + 3 ' -e ' 2 * 3 ' -e ' 2 ^ 3 '
Rscript -e ' 2 + 3; 2 * 3; 2 ^ 3 '

# Run R file
Rscript myscript.R
Rscript -e 'source("myscript.R")'

# Render
Rscript -e 'library(rmarkdown); render("document.Rmd")'

# reading arguments ('n', 'mean', 'sd')


# Examp.R
args <- commandArgs(TRUE)

n <- as.numeric(args[1])
mean <- as.numeric(args[2])
sd <- as.numeric(args[3])

x <- rnorm(n, mean, sd)


cat(x, '\n')

# Command line:
Rscript Examp.R arg1 arg2 arg3

4 Sometime I Write…
R Prepare Peablog

3. Install and load Packages


# install an R package
install.packages("package")

# install more than a package


pckg <- c("dplyr", "data.table")
install.packages(pckg, dependencies = TRUE)

# devtools and install from github


install.packages("devtools")
library(devtools)

install_github("name/remote_repo")

# using functions in packages


packagename::functionname()

# load packages
library(pckg_name)

# data in packages
packagename::data_name

# packages list and remove


installed.packges()
remove.packages("pckg_name")

# update
old.packages()
install.packages("pkgs")
update.packages()

# unload a package
detach("package:name", unload = TRUE)

4. Help
# Help
?function
help(function, package = "pkg_name")
help(package = "pkg_name")

5. Rstudio shorcut
# Character
%>%: Ctrl + Shift + M
<- : Alt + -

# Comment/Uncomment
Ctrl + Shift + C

# Select
Shift + [Arrow]

Alt + Shift + Left/Right

Shift + PageUp/PageDown
Ctrl + A

# Delete
Ctrl + D: Delete current line
Ctrl + Backspace

Sometime I Write… 5
R Prepare Peablog
# Code snippet
Tab/Ctrl + Up

# Run
Ctrl + Enter # Run code selection
Ctrl + Shift + Enter #
Ctrl + Shift + S # Run all file
Ctrl + Shift + F10 # Restart R version
Ctrl + Alt + B # Run From beginning --> Curren tline
Ctrl + Alt + E # Run From Current line --> End
Ctrl + Alt + R # Run Current Document
Ctrl + Shift + P # Re-run Previous Region

# Other
fun --> tab: # Tạo nhanh functionn
Ctrl + Alt + Click # Multi cursor
Ctrl + Shift + / # Ngắt Comment

# Hàm View(Data_set)

# Clear console
Ctrl + L

6. Others
# Thông tin về R
sessionInfo()

# Workspace
ls()
rm(list = object_vector)
rm(object)

# Data in package
data()
data(pacakge = "pkg_name")
View(dataset)

6 Sometime I Write…
R Prepare Peablog

CHAPTER 3: CREATE A REPORT


1. Markdown
1.1. Cấu trúc một file R markdown
Cấu trúc một file R Markdown gồm 3 nội dung chính:
 YAML
 Text dưới dạng Markdown
 Code chunks chứa các mã
Cơ chế hoạt động:

File Rmd được đưa vào Knitr để biên dịch thành file markdown thông qua lệnh
render. Sau đó file md được chuyển đến pandoc để biên dịch thành các file cuối cùng
như pdf, word, html,…
1.2. Code chunks
Có một số cách để thêm code chunks vào R markdown như sau:
 Ctrl + Alt + I
 Nút thêm Chunks trong giao diện Rstudio
 Thủ công thông qua: ```{r} code here ```
Options:
 include = FALSE: Không hiển thị code và kết quả, kết quả có thể được sử dụng
trong các chunks khác
 echo = FALSE: Không hiển thị code
 eval = FALSE: Không chạy code
 results = “hide”: Không hiển thị kết quả
 cache = TRUE: Sử dụng bộ nhớ đệm
 warning = FALSE: Không hiển thị warning
 message = FALSE: Không hiển thị message
 error = FALSE: Không hiển thị error
 label
 ref.label = “label”: Lấy mã từ một chunks đã được gán nhãn
 fig.cap
 fig.weight
 fig.height

Sometime I Write… 7
R Prepare Peablog
#Phim tat: Ctrl + Alt + I
# Chunk

```{r chunk_name}
```

# Hiện code, không chạy code


eval = FALSE

# Chạy Code:

# Không hiện code


echo = FALSE

# Không hiện Kết quả


results = “hide”:

# Không hiện Code + Kết quả


include = FALSE

# Tắt thông báo


message = FALSE
warning = FALSE
error = FALSE

# Cache
cache = TRUE

# chunk option

```{r global_options, include=FALSE}


knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path='Figs/',
echo=FALSE, warning=FALSE, message=FALSE)
```
1.3. Inline codes
Chúng ta có thể sử dụng code ngay trong paragraph thông qua: `r code_here`
Ngoài R ra thì R markdown cũng hỗ trợ một số ngôn ngữ khác như: Python, SQL,
Rcpp, Bash, Stan, Javascript, CSS.
1.4. Params
Chúng ta có thể khai báo trước các tham số trong YAML sau đó sử dụng nó trong các
code chunks. Ví dụ như tham số data khai báo tập dữ liệu sẽ sử dụng.
---
params:
data: "Hawais"
---

# Sử dụng params:
params$data

1.5. Tables
Chúng ta có thể sử dụng Kable để định dạng lại các bảng, kết quả trong R:
```{r echo = FALSE, results = 'asis'}
library(knitr)
kable(mtcars[1:5, ], caption = "A knitr kable.")

8 Sometime I Write…
R Prepare Peablog
1.6. Cú pháp Markdown
# Cú pháp markdown

*In nghieng*
**In dam**
*** Vua in dam vua in nghieng ***

Chi so duoi: ~chiso~


Chi so tren: ^chiso^

danh dau van ban: `inline code`


Code in code: `` `code` ``

link: [text](link)
image: ![alt text or image title](path/to/image)

<!--Foot Note -->


^[This is a footnote.]

A footnote [^1]
[^1]: Here is the footnote.

## Header

```
# First-level header
## Second-level header
### Third-level header

# Preface {-}

## List

- one item
- one item
- one item
- one item
- one item

1. the first item


2. the second item
3. the third item

## Quote

> "I thoroughly disapprove of duels. If a man should challenge me,


I would take him kindly and forgivingly by the hand and lead him
to a quiet place and kill him."
>
> --- Mark Twain

```
This text is displayed verbatim / preformatted
```

## Mathjax
$TeX$
$$TeX$$

## bibiography: file.bib
`[@key]`
`# Reference`

Sometime I Write… 9
R Prepare Peablog

2. Định dạng bảng cho kết quả trả về


library("stargazer")
# type = "html" cho đầu ra html
# mặc định là cho đầu ra latex

# Bảng data
stargazer(both2, type = "html",
summary = FALSE,
rownames = FALSE,
colnames = FALSE)

# Xoay bảng với flip


stargazer(both, type = "html", flip = TRUE)

# Kết quả hồi quy: fit


stargazer(fit1, fit2, type = "html", style = "qje")

# Một số options
stargazer(output, output2, type = "html",
ci = TRUE,
ci.level = 0.90,
ci.separator = " @@ ",
intercept.bottom = FALSE
title = "These are awesome results!",
covariate.labels = c("Temperature", "Wind speed", "Rain (inches)",
"2nd quarter", "3rd quarter", "Fourth quarter"),
dep.var.caption = "A better caption",
dep.var.labels = "Flight delay (in minutes)",
model.numbers = FALSE,
column.labels = c("Good", "Better"),
column.separate = c(2, 2),
add.lines = list(c("Fixed effects?", "No", "No"),
c("Results believable?", "Maybe", "Try again later")))

3. PDF Reports
3.1. Tùy chọn YAML
title: "Habits"
author: John Doe
date: March 22, 2005
output:
pdf_document:
keep_tex: yes
latex_engine: xelatex
citation_package: natbib
fig_caption: true
df_print: kable
highlight: tango
number_sections: true
toc: true
toc_depth: 2
includes:
in_header: preamble.tex
subparagraph: true
urlcolor: black
linkcolor: black
bibliography: [book.bib, packages.bib]
biblio-style: "apalike"
link-citations: yes
geometry: "left=2.5cm, right=3cm, top=2.5cm, bottom=2.5cm, a4paper"
monofont: "Source Code Pro"
monofontoptions: "Scale=0.7"
---

10 Sometime I Write…
R Prepare Peablog
# References

```{r include=FALSE}
knitr::write_bib(c(
.packages(), 'bookdown', 'knitr', 'rmarkdown', 'htmlwidgets', 'webshot',
'DT', 'miniUI', 'tufte', 'servr', 'citr', 'rticles'
), 'packages.bib')
```

3.2. Định dạng đầu ra dạng Latex – preamble.tex


% Table
\usepackage{booktabs}
\usepackage{longtable}

% pdf
\usepackage{pdfpages}

% Căn lề, khoảng cách dòng


\renewcommand{\baselinestretch}{1.0}

% Không thụt đầu dòng


\setlength{\parindent}{0pt}

%
\usepackage[none]{hyphenat}

% Font
\usepackage{fontspec}
\setmainfont{Calibri}
\usepackage{polyglossia}
\setmainlanguage{vietnamese}

% Set font family: Roman or San serif


% \renewcommand{\familydefault}{\sfdefault}
% \renewcommand{\familydefault}{\rmdefault}
% \setromanfont{Times New Roman}
% \setsansfont{Calibri}

% Kích thước font


\usepackage{scrextend}
\changefontsizes{14pt}

% Titlesec-----------------------------------------------
\usepackage{titlesec}

% Edit title font


\newfontfamily{\titlefont}{Cambria}
\newfontfamily{\tocfont}{Cambria}

% Tùy chỉnh khoảng cách giữa các title


\titlespacing*{\section}{0pt}{0pt}{0pt}
\titlespacing*{\subsection}{0pt}{0pt}{0pt}
\titlespacing*{\subsubsection}{0pt}{0pt}{0pt}

% Các phần còn lại


\titleformat{\section}
{\normalfont\large\bfseries\titlefont}{\thesection.}{0.25em}{}
\titleformat{\subsection}
{\normalfont\large\bfseries\titlefont}{\thesubsection.}{0.25em}{}
\titleformat{\subsubsection}
{\normalfont\normalsize\bfseries\titlefont}{\thesubsubsection.}{0.25em}{}
% Table of Content
\usepackage{tocloft,calc}

Sometime I Write… 11
R Prepare Peablog

% Part, Chapter, section, subsection in toc


\renewcommand{\cftsecfont}{\tocfont}
\renewcommand{\cftsecpagefont}{\tocfont}

\renewcommand{\cftsubsecfont}{\tocfont}
\renewcommand{\cftsubsecpagefont}{\tocfont}

% Chỉnh sửa khoảng cách


\renewcommand{\cftsecaftersnum}{.}
\renewcommand{\cftsubsecaftersnum}{.}

\setlength{\cftsecnumwidth}{1.8em}
\setlength{\cftsubsecnumwidth}{2.5em}

\setlength{\cftsecindent}{0em}
\setlength{\cftsubsecindent}{1.8em}

\setlength{\cftbeforesecskip}{0.25ex}
\setlength{\cftbeforesubsecskip}{0.25ex}

% Change caption
\usepackage{caption}
\captionsetup[figure]{labelfont={bf},labelformat={default},name={Fig.}}
\captionsetup[table]{labelfont={bf},labelformat={default},name={Tab.}}

% Xetex---------------------------------------------------
\ifxetex
\usepackage{letltxmacro}
\setlength{\XeTeXLinkMargin}{1pt}
\LetLtxMacro\SavedIncludeGraphics\includegraphics
\def\includegraphics#1#{% #1 catches optional stuff (star/opt. arg.)
\IncludeGraphicsAux{#1}%
}%
\newcommand*{\IncludeGraphicsAux}[2]{%
\XeTeXLinkBox{%
\SavedIncludeGraphics#1{#2}%
}%
}%
\fi

4. Beamer
4.1. YAML
---
title: "Untitled"
author: "Andysth"
date: "Tuesday, February 06, 2018"
output:
beamer_presentation:
incremental: true
theme: "Metropolis"
fig_caption: true
df_print: kable
keep_tex: true
toc: true
includes:
in_header: header.tex
---

12 Sometime I Write…
R Prepare Peablog
4.2. Header.tex
% Table
\usepackage{booktabs}
\usepackage{longtable}

% pdf
\usepackage{pdfpages}

% Font
\usepackage{polyglossia}
\setmainlanguage{vietnamese}

% Change caption
\usepackage{caption}
\captionsetup[figure]{labelfont={bf},labelformat={default},name={Fig.}}
\captionsetup[table]{labelfont={bf},labelformat={default},name={Tab.}}

% Xetex---------------------------------------------------
\ifxetex
\usepackage{letltxmacro}
\setlength{\XeTeXLinkMargin}{1pt}
\LetLtxMacro\SavedIncludeGraphics\includegraphics
\def\includegraphics#1#{% #1 catches optional stuff (star/opt. arg.)
\IncludeGraphicsAux{#1}%
}%
\newcommand*{\IncludeGraphicsAux}[2]{%
\XeTeXLinkBox{%
\SavedIncludeGraphics#1{#2}%
}%
}%
\fi

5. HTML Documents
5.1. HTML
Đoạn dưới đây là phần YAML cho một tài liệu HTML cơ bản.
---
title: "HTML_template"
author: "Tuyen pcf"
date: "Monday, February 05, 2018"
output:
html_document:
theme: flatly
highlight: tango
code_folding: hide
fig_caption: true
number_sections: true
toc: true
toc_float:
collapsed: false
toc_depth: 3
css: styles.css
---
6. Word Documents
---
title: "..."
output:
word_document:
reference_docx: mystyles.docx
---

Sometime I Write… 13
R Prepare Peablog

7. Slidify
7.1. Các thao tác cơ bản
# Cai dat package can thiet
library(devtools)
install_github('slidify', 'ramnathv')
install_github('slidifyLibraries', 'ramnathv')

# Load package
library(slidify)

# Tạo project
author("myproject")

# Chỉnh sửa YAML, trình bày nội dung

# Build, tạo slide:


slidify("index.Rmd")

# Push lên github

7.2. Tùy chỉnh YAML


---
title : R for Presentation
subtitle : Stunning presentations from R markdown
author : Tuyen mfe
job : Data Analyst
framework : io2012
widgets : [mathjax, bootstrap]
mode : selfcontained
knit : slidify::knit2slides
---

7.3. CSS
Trong thư mục assets/css ta tạo file custom.css, các tùy chỉnh về định dạng thực hiện
trong file này:
@import
url('https://fonts.googleapis.com/css?family=Cuprum:400,400i,700,700i|Lora:
400,400i,700,700i|Noto+Serif:400,400i,700,700i&subset=cyrillic,cyrillic-
ext,greek,greek-ext,latin-ext,vietnamese');

/* title side */

.title-slide {
background-color: #FFFFFF;
/* background-image:url(http://goo.gl/EpXln); */
}

.title-slide hgroup > h1 {


font-family: 'Noto Serif', serif;
font-weight: 700;
font-size: 55px;
color: #003E61;
}

.title-slide hgroup > h2 {


font-family: 'Noto Serif', serif;
font-weight: 700;
color: #003E61;
}

14 Sometime I Write…
R Prepare Peablog
.title-slide hgroup p {
line-height: 1.3;
font-family: 'Lora', serif;
font-style: italic;
margin-top: 150px;
}

slides > slide.dark {


background: #003E61 !important;
}

slide.segue h2 {
font-family: 'Noto Serif', serif;
font-weight: 700;
}

slide:not(.segue) h2 {
font-family: 'Noto Serif', serif;
font-weight: 700;
color: #003E61;
margin-top: 0px;
}

h3 {
font-family: 'Noto Serif', serif;
font-weight: 700;
background-color: #31869B;
color: #FFFFFF;
text-indent: 12px;
}

article p {
font-family: 'Noto Serif', serif;
color: #171717;
font-size: 24px;
}

article li {
font-family: 'Noto Serif', serif;
color: #171717;
font-size: 24px;
}

ol li {
font-family: 'Noto Serif', serif;
color: #171717;
}

ul > li:before {
margin-left: -0.5em;
font-size: -webkit-xxx-large;
color: cadetblue;
}

ul li {
margin-left: 0.0em;
}

Sometime I Write… 15
R Prepare Peablog
ul li ul li:before {
content: '\00b0';
font-size: x-large;
margin-top: 5px;
margin-left: -1.0em;
}

ul ul {
margin-top: 0.25em;
}

ol {
margin: 0 0 10px 35px;
}

.leftcol {
text-align: left;
}

pre code {
color: #747474;
}

::selection {
color: #FFFFFF;
background-color: #538622;
}

slides > slide {


overflow: scroll;
}

7.4. Tùy chỉnh assets/layouts


File carousel.html
---
layout: slide
---

{{{ slide.content }}}


<div id="{{slide.id}}-carousel" class="carousel slide {{slide.class}}">
<!-- Indicators -->
<ol class="carousel-indicators">
{{# slide.blocks }}
<li data-target="#{{slide.id}}-carousel" data-slide-to="{{num}}"
class="{{class}}"></li>
{{/ slide.blocks }}
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
{{# slide.blocks }}
<div class="item {{class}}">
<img src="{{img}}" alt="{{alt}}" style="margin: auto; max-height:
500px; min-height: 500px;">
<div class="carousel-caption">{{{ content }}}</div>
</div>
{{/ slide.blocks }}
</div>
<!-- Controls -->
<a class="left carousel-control" href="#{{slide.id}}-carousel" data-
slide="prev">&lsaquo;</a>

16 Sometime I Write…
R Prepare Peablog
<a class="right carousel-control" href="#{{slide.id}}-carousel" data-
slide="next">&rsaquo;</a>
</div>

File slide.html
<slide class="{{ slide.class }}" id="{{ slide.id }}"
style="background:white;">
{{# slide.header }}
<hgroup>
{{{ slide.header}}}
</hgroup>
{{/ slide.header }}
<article data-timings="{{ slide.dt }}">
{{{ slide.content }}}
</article>
<!-- Presenter Notes -->
{{# slide.pnotes }}
<aside class="note" id="{{ id }}">
<section>
{{{ html }}}
</section>
</aside>
{{/ slide.pnotes }}
</slide>

File slidebg.html
<slide class="{{ slide.class }}" id="{{ slide.id }}" style="background:{{{
slide.bg }}};">
{{# slide.header }}
<hgroup>
{{{ slide.header}}}
</hgroup>
{{/ slide.header }}
<article data-timings="{{ slide.dt }}">
{{{ slide.content }}}
</article>
<!-- Presenter Notes -->
{{# slide.pnotes }}
<aside class="note" id="{{ id }}">
<section>
{{{ html }}}
</section>
</aside>
{{/ slide.pnotes }}
</slide>

File twocol.html
---
layout: slide
---
{{{ slide.content }}}
<div style='float:left;width:48%;' class='leftcol'>
{{{ slide.left.html }}}
</div>
<div style='float:right;width:48%;'>
{{{ slide.right.html }}}
</div>

Sometime I Write… 17
R Prepare Peablog
7.5. Trình bày nội dung
List trong slide (ul, ol):
## Example

1. Edit YAML front matter


* Write using R Markdown
* Use an empty line followed by three dashes to separate slides!

Trang tiêu đề:


--- .dark .segue .nobackaground
## Title here

Hai cột:
--- &twocol
## Tiêu đề trang này

*** =left
### Header cột trái
* Nội dung ở đây

*** =right
### tiêu đề cột phải
* Thêm nội dung ở đây nữa

Căn giữa:
--- &vcenter
## Can giua

Vài dòng text ở đây sẽ được căn giữa màn hình

R code chunk:
---
```{r}
```

Công thức toán:


---
## Công thức toán học kèm theo text
$$E=mc^2\text{ (where c = 299,792,458 m/s)}$$
\[ PV=nRT \;\; (R = \text{the ideal gas constant} = 8.3144621 \; JK^{-1}m

Chèn ảnh
--- &vcenter
## Dưới đây là một hình ảnh
<img src="./assets/img/Tauntaun.png" alt="Sorry, the link must have moved."
title="http://familyguy.wikia.com/" width="600">

--- &slidebg bg:url(./assets/img/Tauntaun.png);background-size:cover

--- &carousel
## Look ma! Slides within slides!

*** {class: active, img: "http://goo.gl/kcRF4e"}


Hình ảnh 1 http://bruce.kus-numa.net/

*** {img: "http://goo.gl/GwVFOh"}


Hình ảnh 2 http://southpark.wikia.com

18 Sometime I Write…
R Prepare Peablog

CHAPTER 4: CREATE A PACKAGE


Một package hiểu đơn giản là tập hợp các hàm, documentation, và dữ liệu được tổ
chức, lưu trữ theo một định dạng nào đó đã được chuẩn hóa.

1. Quy trình làm việc cơ bản


# Install and Build by devtools package

# Sử dụng R
install.packages(devtools)
library(devtools)

# Tạo document bởi roxygen2


document()

# Build package
build()

# Install
install()

# Check
check()

# Sau khi sử dụng quy trình trên thì có thể gọi package như bình thường

# Push to github
# Sử dụng git để push lên github
# Install package from git
install_github("author/package")

2. Cấu trúc cơ bản của một thư mục package


Về cơ bản, một package gồm các folder và file sau:
 Thư mục R chứa các file R
 Thư mục man chứa tài liệu về các hàm
 File DESCRIPTION
 File NAMESPACE
 Thư mục data chứa data
 Thư mục inst chứa các file khác

3. File DESCRIPTION
Khi làm việc với Description ta cần phân biệt giữa Depends, Imports và Suggest. Với
các gói trong Depends, khi ta gọi một gói thì các gói trong Depends của gói đó cũng
được gọi (Sử dụng library() or required()). Với các gói trong Imports, khi ta gọi một gói
thì các gói trong này không được gọi. Tuy nhiên khi ta cái đặt một gói, các gói trong
Depends và Imports nếu chưa cài đặt sẽ được cài đặt. Nếu gói của chúng ta có sử
dụng các hàm đến từ các gói khác, ta nên khai báo nó trong Imports. Đối với Suggest,
sẽ đại diện cho các gói chứa các tài liệu, hàm, dữ liệu được sử dụng bởi các ví dụ. Các
gói trong suggest không được cài đặt và gọi khi ta cài đặt và gọi một gói.

Sometime I Write… 19
R Prepare Peablog
Khi viết DESCRIPTION, các giá trị trên nhiều dòng của một thẻ cần thụt đầu dòng 4
space.
Để tự động thêm các package vào file DESCRIPTION:
# Để tự động thêm các package vào Imports và Suggests trong DESCRIPTION, ta
sử dụng:

devtools::use_package("dplyr") # Defaults to imports


#> Adding dplyr to Imports
#> Refer to functions with dplyr::fun()
devtools::use_package("dplyr", "Suggests")
#> Adding dplyr to Suggests
#> Use requireNamespace("dplyr", quietly = TRUE) to test if package is
#> installed, then use dplyr::fun() to refer to functions.

Cấu trúc đối với Author


# Author:
# role có 4 option: cre (người sáng tạo or bảo trì), aut (các tác giả đóng
góp), ctb (những người đóng góp như vá lỗi,...), cph (người giữ bản quyền
nếu k phải là cre)
Authors@R: person("Hadley", "Wickham", email = "hadley@rstudio.com",
role = c("aut", "cre"))

Authors@R: c(
person("Hadley", "Wickham", email = "hadley@rstudio.com", role =
"cre"),
person("Winston", "Chang", email = "winston@rstudio.com", role =
"aut"))

Authors@R: as.person(c(
"Hadley Wickham <hadley@rstudio.com> [aut, cre]",
"Winston Chang <winston@rstudio.com> [aut]"
))

Ví dụ:
Package: pkg_name
Title: ......
Version: 0.1
Date: 2014-08-27
Author: Name <Email>
Description: ......

Depends:
R (>= 2.15),
qtl (>= 1.30-4)
Imports:
jsonlite,
graphics,
stats,
utils
Suggests:
knitr,
devtools,
roxygen2,
testthat
URL: http://yihui.name/knitr/
BugReports: https://github.com/yihui/knitr/issues
License: What license is it under?
LazyData: true

20 Sometime I Write…
R Prepare Peablog

4. Thư mục R và các file R


Khi xây dựng một hàm, nếu ta muốn người khác có thể sử dụng hàm đó ta nên dùng
thẻ export trước mỗi hàm đó. Chỉ nên sử dụng export với các hàm chính.
#' @export
your_fun <- function()

5. File NAMESPACE
Khi ta muốn sử dụng các hàm từ gói khác, ta có thể sử dụng cú pháp: pkg::fun mà
không cần gọi hàm, nhưng phải khai báo trong Imports or trong Depends trong file
Description.
Ngoài cách này, ta còn có thể sử dụng thẻ import và importFrom. Nếu ta sử dụng
toàn bộ các hàm của một package nào đó ta sử dụng thẻ import. Nếu ta chỉ sử dụng
một vài hàm, ta sử dụng thẻ importFrom. Các package này cũng phải được khai báo
trong Depend or Imports:
# Các hàm được sử dụng bởi import, importFrom từ các gói khác có thể được
sử dụng trực tiếp mà không cần ::

#' @importFrom pkg fun1 fun2 fun3


#' @import pkg

Tóm lại ta có công thức tổng quát:


 Nếu bạn cần đính kèm gói với library():Depends
 Nếu bạn sử dụng chức năng từ gói ( ::, @importhay @importFrom) nhưng
không cần phải sử dụng library():Imports
 Nếu nó không được sử dụng trong mã nhưng được sử dụng trong ví dụ, họa
tiết hoặc kiểm tra: Suggests

6. Thư mục man và tạo tài liệu bởi roxygen2


# Sử dụng @@ sẽ trả về @, ngược lại sử dụng @ sẽ làm R hiểu theo một ý
nghĩa khác
# Đoạn đầu tiên là tiêu đề của tài liệu
# Đoạn 2 là Description
# Từ Đoạn 3 là đi vào chi tiết
# Thụt lề đối với các dòng tiếp theo của các thẻ

#' Illustration of crayon colors


#'
#' Creates a plot of the crayon colors in \code{\link{brocolors}}
#'
#' @param method2order method to order colors (\code{"hsv"} or
\code{"cluster"})
#' @param cex character expansion for the text
#' @param mar margin paramaters; vector of length 4 (see
\code{\link[graphics]{par}})
#'
#' @return None
#'
#' @examples
#' plot_crayons()
#'
#' @export

Sometime I Write… 21
R Prepare Peablog

7. Thư mục Data


Các file dữ liệu được lưu trữ trong thư mục Data, là các file có đuô .Rdata.
# Folder: data
save(mydata, file="data/mydata.RData")
save(priming.s1, priming.s2, simulation.A, simulation.B, file =
"data/priming_all.RData")

Tạo tài liệu cho data:


Để tạo tài liệu cho data, ta tạo một file data_name.R trong thư mục R và sử dụng
roxygen2 để tạo tài liệu cho data. Kết thúc file phải có tên của đối tượng, ở đây là tên
data frame:
# Sau đó tạo một file .R cùng tên với tập dữ liệu trong thư mục R
# Ví dụ mô tả về Tập dữ liệu sử dụng roxygen2
#' Study 1 of Phillips et al. (2017)
#'
#' This dataset contains fictional data from study 1 of a priming
experiment.
#'
#'
#' @format A data frame containing 1000 rows and 6 columns.
#' \describe{
#' \item{sex}{(string) - The participant's age}
#' \item{price}{price, in US dollars}
#' \item{age}{(numeric) - Participant's sex}
#' \item{prime}{(string) - The participant's priming condition (elderly
or neutral)}
#' \item{time}{(numeric) - Amount of time (in seconds) it took for a
participant to walk down the hall].}
#' }
#' @details Each row corresponds to a participant. Participants were
randomly assigned....
#' @source Experiment conducted at the Economic Psychology lab
\url{http://www.diamondse.info/}
#' @examples
#'
#' # Histogram of participant ages
#' hist(priming.s1$age)
#'
#' # t.test comparing the walking time of participants in each condition.
#' # should give a p-value of .03
#'
#' t.test(formula = time ~ prime,
#' data = priming.s1)

"priming.s1"

22 Sometime I Write…
R Prepare Peablog

CHAPTER 5: WORKING WITH DATA WEB


1. Read data from internet, zip
# Download và giải nén toàn bộ file zip
download.file(url, dest = "dataset.zip", mode = "wb")
unzip("dataset.zip", exdir = "./")

# Danh sách các file trong folder được giải nén


list.files("folder_name")

# Nếu chúng ta biết file muốn giải nén thay vì toàn bộ


download.file(url, dest = "dataset.zip", mode = "wb")
unz("dataset.zip", "folder_name/file.csv")

# Nếu chúng ta không muốn download về và lưu vào máy


temp <- tempfile()
download.file("url", temp)
unz(temp, "folder_name/file.csv")
unlink(temp)

# Hàm getHTMLLinks liệt kê toàn bộ link tìm được từ web, mỗi link là 1 phần
tử của vector
# Sau khi có link, ta sử dụng vòng lặp để download data
# Sử dụng str_detect(str_vect, pattern) trả về TRUE nếu phần tử của vecter
chứa chuỗi tìm kiếm
library(XML)
library(stringr)
links <- getHTMLLinks(url)
links_data <- links[str_detect(links, ".csv")]

2. Scrapping HTML data


Nội dung của HTML được viết giữa các thẻ có dạng:
<tagname>content</tagname>

Các thẻ cơ bản như: <h1>, <h2>,..., <h6>, <p>, <ul>, <ol>, <li>, <div>,
<table>

#Loading the rvest package


library('rvest')

#Specifying the url for desired website to be scrapped


url <-
'http://www.imdb.com/search/title?count=100&release_date=2016,2016&title_ty
pe=feature'

#Reading the HTML code from the website


webpage <- read_html(url)

#Using CSS selectors to scrap the rankings section


rank_data_html <- html_nodes(webpage,'.text-primary')

#Converting the ranking data to text


rank_data <- html_text(rank_data_html)

#Let's have a look at the rankings


head(rank_data)

#Data-Preprocessing: Converting rankings to numerical


rank_data<-as.numeric(rank_data)

# Xử lý tương tự với các biến khác, sau đó gộp lại thành một data frame

Sometime I Write… 23
R Prepare Peablog

3. Scrapping HTML table data


tbls_ls <- webpage %>%
html_nodes("table") %>%
.[3:4] %>%
html_table(fill = TRUE)

# empty list to add table data to


tbls2_ls <- list()

# scrape Table 2. Nonfarm employment...


tbls2_ls$Table1 <- webpage %>%
html_nodes("#Table2") %>%
html_table(fill = TRUE) %>%
.[[1]]

# Table 3. Net birth/death...


tbls2_ls$Table2 <- webpage %>%
html_nodes("#Table3") %>%
html_table() %>%
.[[1]]

4. Read data from APIs, XML, JSON


4.1. Quy trình làm việc cơ bản
Quy trình làm việc với dữ liệu web được lưu trữ trong các APIs khá là phức tạp. Nếu
một APIs đã có các packages trong R thì ta đọc hướng dẫn liên quan đến packages đó.
Nếu một APIs chưa có các packages thì chúng ta sử dụng httr, jsonlite, xml2 để lấy ra
các dữ liệu mong muốn.
Bước đầu tiên của quy trình là sử dụng httr để gửi GET() đến APIs và nhận lại kết quả.
Bước thứ hai là xác định xem kết quả trả về ở dạng XML hay là JSON.
Bước thứ ba ta đi xử lý để thu được định dạng chính xác ở dạng Json hoặc xml.
Bước cuối cùng là sử dụng các hàm để lấy kết quả từ trên.
4.2. Làm việc với httr
# GET
# Load the httr package
library(httr)

# Make a GET request to http://httpbin.org/get


get_result <- GET("http://httpbin.org/get")

# Print it to inspect it
get_result

# Response [http://httpbin.org/get]
# Date: 2018-07-03 12:01
# Status: 200
# Content-Type: application/json
# Size: 268 B
# {"args":{},"headers":{"Accept":"application/json, text/xml,
application/xml, ...

24 Sometime I Write…
R Prepare Peablog
# POST
# Load the httr package
library(httr)

# Make a POST request to http://httpbin.org/post with the body "this is a


test"
post_result <- POST("http://httpbin.org/post", body = "this is a test")

# Print it to inspect it
post_result

# Response [http://httpbin.org/post]
# Date: 2018-07-03 12:04
# Status: 200
# Content-Type: application/json
# Size: 348 B
# {"args":{},"data":"this is a
test","files":{},"form":{},"headers":{"Accept":"...

4.3. Làm việc với GET


Mặc dù chúng ta có thể sử dụng httr để làm nhiều việc như GET(), POST(), DELETE(),…
Tuy nhiên chúng ta tập chung vào lấy dữ liệu từ APIs là chính, vì vậy mà ta chỉ quan
tâm đến sử dụng GET().
Một số hàm chính khi làm việc với GET là: GET(), http_type(), content(), str(),
http_error()
 Hàm GET() gửi yêu cầu đến API
 Hàm http_type() xác định định dạng đầu ra từ hàm GET()
 Hàm content() trả về nội dung từ hàm GET(), đối số as = “parsed” tự động xác
định loại đầu ra và xử lý, đối số as = “text” trả về kết quả ở dạng text
 Hàm str() sử dụng để xem kết quả của content
 Hàm http_error() trả về TRUE nếu yêu cầu bị lỗi
# Make a GET request to url and save the results
pageview_response <- GET(url)

# Call content() to retrieve the data the server sent back


pageview_data <- content(pageview_response)

# Examine the results with str()


str(pageview_data)

# Kết quả:
List of 1
$ items:List of 2
..$ :List of 7
.. ..$ project : chr "en.wikipedia"
.. ..$ article : chr "Hadley_Wickham"
.. ..$ granularity: chr "daily"
.. ..$ timestamp : chr "2017010100"
.. ..$ access : chr "all-access"
.. ..$ agent : chr "all-agents"
.. ..$ views : int 45
..$ :List of 7
.. ..$ project : chr "en.wikipedia"
.. ..$ article : chr "Hadley_Wickham"
.. ..$ granularity: chr "daily"

Sometime I Write… 25
R Prepare Peablog
# http_error()
fake_url <- "http://google.com/fakepagethatdoesnotexist"

# Make the GET request


request_result <- GET(fake_url)

# Check request_result
if(http_error(request_result)){
warning("The request failed")
} else {
content(request_result)
}

4.4. Một số vấn đề khác khi làm việc với GET


# Url của APIs có thể gồm 2 dạng:
# Dạng thư mục: http://swapi.co/api/vehicles/12
GET(paste("http://swapi.co", "api", "vehicles", "12", sep = "/"))

# Dạng key = value: fakeurl.com/api.php?fruit=peaches&day=thursday


GET("fakeurl.com/api.php", query = list(fruit = "peaches", day =
"thursday"))

# Thêm thông tin người gửi yêu cầu qua user_agent()


# Do not change the url
url <- "https://wikimedia.org/api/rest_v1/metrics/pageviews/per-
article/en.wikipedia/all-access/all-
agents/Aaron_Halfaker/daily/2015100100/2015103100"

# Add the email address and the test sentence inside user_agent()
server_response <- GET(url, user_agent("my@email.address this is a test"))

# Một số API chỉ cho gửi giới hạn số yêu cầu trong một thời gian nhất định
# tạm dừng 15s trước khi chạy lệnh tiếp theo
Sys.sleep(15)

4.5. Xử lý dữ liệu Json


# Ví dụ:
[{
"first_name": "Jason",
"last_name": "Bourne",
"occupation": "Spy"
},
{
"first_name": "Jason",
"last_name": "Voorhees",
"occupation": "Mass murderer"
}]
# Kiểm tra định dạng đầu ra
http_type(get_result)

# Chuyển đổi kết quả qua JSON, 2 cách


fromJSON(content(get_result, as = "text"))
content(get_result, as = "parsed")

# Xem kết quả:


str(content(resp_json), max.level = 4)

List of 2
$ continue:List of 2
..$ rvcontinue: chr "20150528042700|664370232"
..$ continue : chr "||"
$ query :List of 1
..$ pages:List of 1

26 Sometime I Write…
R Prepare Peablog
.. ..$ 41916270:List of 3
.. .. ..$ pageid : int 41916270
.. .. ..$ title : chr "Hadley Wickham"
.. .. ..$ revisions:List of 5

# Xử lý kết quả phân tích json với rlist package


# list.select() trả về 1 list, list.stack() trả về 1 data.frame
# Muốn lấy kết quả từ revisions:
revs <- content(resp_json)$query$pages$`41916270`$revisions

# Cách 1:
# user, timestamp là các biến,
user_time <- list.select(revs, user, timestamp)
list.stack(user_time)

# Cách 2:
revs %>% bind_rows %>% select(user, timestamp)

4.6. Xử lý dữ liệu XML


# Ví dụ:
# <tag attri = >
# <tag> Content</tag>
<?xml version="1.0" encoding="UTF-8"?>
<movies>
<title>"Star Wars"</title>
<movie episode = "IV">
<title>A New Hope</title>
<year>1977</year>
</movie>
<movie episode = "V">
<title>The Empire Strikes Back</title>
<year>1980</year>
</movie>
</movies>
# Load package
library(xml2)

# Kiểm tra xem output có phải là XML không


http_type(get_result)
content(get_result, as = "text")

# Xem kết quả dạng XML:


xml_structure(read_xml(content(get_result, as = "text")))

# Trích kết quả content: <tag>Content</tag>


# /node_name chỉ định các node có thẻ node_name ở cấp hiện tại
# //node_name chỉ định các node có thẻ node_name ở cấp bất kỳ thấp hơn mức
hiện tại

# Sử dụng xml_find_all(read_xml(), "xpath"), trả về kết quả ở dạng node


xml_find_all(rev_xml, "/api/query/pages/page/revisions/rev")
xml_find_all(rev_xml, "//rev")
xml_find_first(rev_xml, "//rev") # Trả về node đầu tiên tìm được

# Sử dụng xml_text(), xml_double(), xml_integer() để lấy nội dung


# Sử dụng /xpath/@attr trong xml_find_all, xml_attr, xml_attrs để lấy thuộc
tính: <tag attri = >
# xml_attr(xml_find_output, "attr"), xml_attrs(xml_find_output)
# xml_attr trả về thuộc tính duy nhất được xác định
# xml_attrs trả về tất cả các thuộc tính tìm được

Sometime I Write… 27

Вам также может понравиться