Chapter 1: R Style Guide: 1. Quy tắc đặt tên
Chapter 1: R Style Guide: 1. Quy tắc đặt tên
Chapter 1: R Style Guide: 1. Quy tắc đặt tên
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
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)
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
)
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 =
# String:
"This is ..."
'Text with "quotes"'
'<a href="http://style.tidyverse.org">A link</a>'
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
}
4. Toán tử Pipes
foo_foo %>%
hop(through = forest) %>%
scoop(up = field_mouse) %>%
bop(on = head)
x %>%
unique() %>%
sort()
Sometime I Write… 3
R Prepare Peablog
# Tạo file
cat(file = "Example.R")
# 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")'
n <- as.numeric(args[1])
mean <- as.numeric(args[2])
sd <- as.numeric(args[3])
# Command line:
Rscript Examp.R arg1 arg2 arg3
4 Sometime I Write…
R Prepare Peablog
install_github("name/remote_repo")
# load packages
library(pckg_name)
# data in packages
packagename::data_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]
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
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}
```
# Chạy Code:
# Cache
cache = TRUE
# chunk option
# 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 ***
link: [text](link)
image: ![alt text or image title](path/to/image)
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
## Quote
```
This text is displayed verbatim / preformatted
```
## Mathjax
$TeX$
$$TeX$$
## bibiography: file.bib
`[@key]`
`# Reference`
Sometime I Write… 9
R Prepare Peablog
# Bảng data
stargazer(both2, type = "html",
summary = FALSE,
rownames = FALSE,
colnames = FALSE)
# 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')
```
% pdf
\usepackage{pdfpages}
%
\usepackage[none]{hyphenat}
% Font
\usepackage{fontspec}
\setmainfont{Calibri}
\usepackage{polyglossia}
\setmainlanguage{vietnamese}
% Titlesec-----------------------------------------------
\usepackage{titlesec}
Sometime I Write… 11
R Prepare Peablog
\renewcommand{\cftsubsecfont}{\tocfont}
\renewcommand{\cftsubsecpagefont}{\tocfont}
\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")
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); */
}
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;
}
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;
}
16 Sometime I Write…
R Prepare Peablog
<a class="right carousel-control" href="#{{slide.id}}-carousel" data-
slide="next">›</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
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
R code chunk:
---
```{r}
```
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">
--- &carousel
## Look ma! Slides within slides!
18 Sometime I Write…
R Prepare Peablog
# Sử dụng R
install.packages(devtools)
library(devtools)
# 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")
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:
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
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 ::
Sometime I Write… 21
R Prepare Peablog
"priming.s1"
22 Sometime I Write…
R Prepare Peablog
# 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")]
Các thẻ cơ bản như: <h1>, <h2>,..., <h6>, <p>, <ul>, <ol>, <li>, <div>,
<table>
# 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
# 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)
# 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":"...
# 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"
# Check request_result
if(http_error(request_result)){
warning("The request failed")
} else {
content(request_result)
}
# 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)
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
# 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)
Sometime I Write… 27