# 常用函式

## System and Environment

| Code            | Description          |
| --------------- | -------------------- |
| `#`             | 註解，程式不執行被註解的部分       |
| `rm(var)`       | 從Environment中移除某個變數  |
| `ls()`          | 列出所有在Environment中的變數 |
| `rm(list=ls())` | 移除所有Environment中的變數  |

### Installing packages

| Code                            | Description   |
| ------------------------------- | ------------- |
| `install.packages('tidyverse')` | 安裝套件到你電腦（需連網） |
| `library(readxl)`               | 載入套件到這個程式來用   |

help(function\_name); # 查詢help，括號內為函式或套件名稱 ?function\_name # 縮寫

print(var) # 列印出該變數的內容 message(msg) # 列印出該變數的內容，但用警告的顏色

## RDA, RData, and RDS

* [`readRDS()`](https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/readRDS): Serialization Interface For Single Objects, paired with `saveRDS()` 。
* [`load()`](https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/load) : Reload Saved Datasets, paired with `save()`. 因為允許儲存多個物件，所以最後一個參數必須特別用`file` 這個參數來指定要存到哪個檔案。如`save(obja, objb, objc, file = file_path)` 。而`saveRDS()` 並不用特別用`file` 參數來指定存在哪個檔案，因為`saveRDS()` 總之只儲存一個物件。

{% embed url="<https://fromthebottomoftheheap.net/2012/04/01/saving-and-loading-r-objects/#:~:text=save()%20does%20the%20same,it%20had%20when%20originally%20serialized>." %}

{% embed url="<https://yihui.org/en/2017/12/save-vs-saverds/>" %}

| Functions                                   | Writing time  | Reading time                                  | File size    |
| ------------------------------------------- | ------------- | --------------------------------------------- | ------------ |
| `write_rds(compress = "gz")`  +`read_rds()` | 1.109 mins    | 39.81 secs                                    | 330.6 mb     |
| `write_rds()` + `read_rds()`                | **30 secs**   | Error: cannot allocate vector of size 12.1 Mb | **3GB**      |
| `saveRDS()`+`readRDS()`                     | 1.12 mins     | Error: cannot allocate vector of size 12.1 Mb | 330.6 mb     |
| `save()` + `load()`                         | **1.11 mins** | Error: cannot allocate vector of size 12.1 Mb | **330.6 mb** |
