從2018年秋季(大二上學期)開始接觸R語言,曾在2019年寒假讀過一遍本書的第一版,感覺受益匪淺,之后遇到問題也曾回頭來查閱這本書,前幾天剛學習過Simulink,趁現在有空再來溫習這本書,回顧一下代碼和各種命令,簡單記錄。
雖然感覺R的功能和用途不如MATLAB廣泛,但是需要派上用場的時候如果能熟練地運用真的是很好的體驗。
- R用方括號[ ]引用數組元素,而MATLAB用圓括號( ),同時使用它倆的時候總搞混;
- R不需要分號來結束語句;
- 如果之前運行過多行代碼,R在Console中輸入↑可同時得到多行,MATLAB在Command Window中輸入↑只能得到單行。
但是它們還是有很多相似之處的:
- 數組下標從1開始,哈哈,和C、Python等不同;
- 都有交互式命令窗口,工作空間;
- 都有實時腳本等,很多很多……

1.1 為何要使用R
- 免費
- 功能全面
- 更新快
- 繪圖強大
- 交互式,方便操作
- 數據導入導出方便
- 語言自然簡單
- 可以被整合到其他語言編寫的應用程序中
- 可運行於多種平台之上
1.2 R的使用
1.2.1 獲取幫助
- help.start() 打開幫助文檔首頁
-
help("foo")或?foo 查看函數 foo 的幫助(引號可以省略)
- example("foo") 函數 foo 的使用示例(引號可以省略)
- help.search("foo")或??foo 以 foo 為關鍵詞搜索本地幫助文檔
- RSiteSearch("foo") 以 foo 為關鍵詞搜索在線文檔和郵件列表存檔
- apropos("foo", mode="function") 列出名稱中含有 foo 的所有可用函數
- data() 列出當前已加載包中所含的所有可用示例數據集
> library(car) 載入需要的程輯包:carData Warning message: 程輯包‘car’是用R版本3.5.2 來建造的 > data()

- vignette() 列出當前已安裝包中所有可用的 vignette 文檔
- vignette("foo") 為主題 foo 顯示指定的 vignette 文檔
1.2.2 工作空間
- getwd() 顯示當前的工作目錄
- setwd("mydirectory") 修改當前的工作目錄為 mydirectory

- ls() 列出當前工作空間中的對象
- rm(objectlist) 移除(刪除)一個或多個對象
- help(options) 顯示可用選項的說明
- options() 顯示或設置當前選項
> x=rnorm(3) > x [1] -0.1284972 0.1003854 -1.8987649 > options(digits=3) > x [1] -0.128 0.100 -1.899
- savehistory("myfile") 保存命令歷史到文件 myfile 中(默認值為.Rhistory)
- loadhistory("myfile") 載入一個命令歷史文件(默認值為.Rhistory)
- save.image("myfile") 保存工作空間到文件 myfile 中(默認值為.RData)
- load("myfile") 讀取一個工作空間到當前會話中(默認值為.RData)
- save(objectlist, file="myfile") 保存指定對象到一個文件中
1.2.3 輸入和輸出
-
source("filename") 在當前會話中執行一個腳本
-
sink("filename")將輸出重定向到文件filename中
sink("sink-examp.txt") i <- 1:10 outer(i, i, "*") sink()

- cat()
Outputs the objects, concatenating the representations. cat performs much less conversion than print.
cat is useful for producing output in user-defined functions.
cat(... , file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE)
fill:a logical or (positive) numeric controlling how the output is broken into successive lines. If FALSE (default), only newlines created explicitly by "\n" are printed. Otherwise, the output is broken into lines with print width equal to the option width if fill is TRUE, or the value of fill if this is numeric. Non-positive fill values are ignored, with a warning.
labels:character vector of labels for the lines printed. Ignored if fill is FALSE.
example:
i<-1:10 text<-c("a","b","c","d") cat(i,file="i.txt",sep="-",fill=10,labels=text)

圖形輸出:
-
bmp("filename.bmp") BMP 文件
-
jpeg("filename.jpg") JPEG 文件
-
pdf("filename.pdf") PDF 文件
-
png("filename.png") PNG 文件
-
postscript("filename.ps") PostScript 文件
-
svg("filename.svg") SVG 文件
- win.metafile("filename.wmf") Windows 圖元文件
i <- 1:10 bmp("ii.bmp") plot(i,i) dev.off()

1.3 包
> .libPaths() [1] "D:/R/R-3.5.1/library" > search() [1] ".GlobalEnv" "tools:rstudio" [3] "package:stats" "package:graphics" [5] "package:grDevices" "package:utils" [7] "package:datasets" "package:methods" [9] "Autoloads" "package:base"
- install.packages() 安裝一個包
- update.packages() 更新已經安裝的包
- library() 載入一個包
- help(package="package_name")
1.4 批處理
reference: https://blog.revolutionanalytics.com/2009/06/running-scripts-with-r-cmd-batch.html
R CMD BATCH myscript.R myscript.Rout
#example.R clotting <- data.frame( u = c(5,10,15,20,30,40,60,80,100), lot1 = c(118,58,42,35,27,25,21,19,18), lot2 = c(69,35,26,21,18,16,13,12,12)) cat("Model data:\n") print(clotting) warning("Model starting") obj <- glm(lot1 ~ log(u), data=clotting, family=Gamma) cat("\nEstimated parameters:\n") coef(summary(obj))
PS C:\Users\lenovo> cd Desktop PS C:\Users\lenovo\Desktop> D:\R\R-3.5.1\bin\R.exe CMD BATCH example.R example.Rout
R version 3.5.1 (2018-07-02) -- "Feather Spray" Copyright (C) 2018 The R Foundation for Statistical Computing Platform: x86_64-w64-mingw32/x64 (64-bit) R是自由軟件,不帶任何擔保。 在某些條件下你可以將其自由散布。 用'license()'或'licence()'來看散布的詳細條件。 R是個合作計划,有許多人為之做出了貢獻. 用'contributors()'來看合作者的詳細情況 用'citation()'會告訴你如何在出版物中正確地引用R或R程序包。 用'demo()'來看一些示范程序,用'help()'來閱讀在線幫助文件,或 用'help.start()'通過HTML瀏覽器來看幫助文件。 用'q()'退出R. [原來保存的工作空間已還原] > clotting <- data.frame( + u = c(5,10,15,20,30,40,60,80,100), + lot1 = c(118,58,42,35,27,25,21,19,18), + lot2 = c(69,35,26,21,18,16,13,12,12)) > cat("Model data:\n") Model data: > print(clotting) u lot1 lot2 1 5 118 69 2 10 58 35 3 15 42 26 4 20 35 21 5 30 27 18 6 40 25 16 7 60 21 13 8 80 19 12 9 100 18 12 > warning("Model starting") Warning message: Model starting > obj <- glm(lot1 ~ log(u), data=clotting, family=Gamma) > cat("\nEstimated parameters:\n") Estimated parameters: > coef(summary(obj)) Estimate Std. Error t value Pr(>|t|) (Intercept) -0.01655438 0.0009275466 -17.84749 4.279149e-07 log(u) 0.01534311 0.0004149596 36.97496 2.751191e-09 > > proc.time() 用戶 系統 流逝 0.25 0.20 0.36
At the same time we can get a file with the suffix .RData.
Or we can just write the following two lines to a .bat file and double-click to run it.
cd C:\Users\lenovo\Desktop D:\R\R-3.5.1\bin\R.exe CMD BATCH example.R example.Rout
#example.R argv<-commandArgs(TRUE) x<-as.numeric(argv[1]) y<-as.numeric(argv[2]) cat("x=",x,"\n") cat("y=",y,"\n") cat("x+y=",x+y,"\n") cat("x^y",x^y,"\n")
PS C:\Users\lenovo> cd Desktop PS C:\Users\lenovo\Desktop> D:\R\R-3.5.1\bin\Rscript.exe example.R 1 2 >output.ROut
Output in output.Rout:
x= 1 y= 2 x+y= 3 x^y 1
1.5 結果的重用
lmfit <- lm(mpg~wt, data=mtcars)
-
summary(lmfit) 顯示分析結果的統計概要
-
plot(lmfit) 生成回歸診斷圖形
總結
