跳轉到內容

R 程式設計/實用程式

來自華夏公益教科書

此頁面包含一些實用程式的資訊。這裡介紹的大多數函式與統計分析無關,但在專案開發中可能有用。許多函式類似於標準的 unix 函式。

系統 (Unix/DOS)

[編輯 | 編輯原始碼]

system()提供對系統 (DOS 或 unix) 的訪問許可權。選項wait=FALSE意味著您不會讓 R 等待任務完成。

一些示例 

  • 您可以使用 unix 將影像從 PS 轉換為 PNGconvert計算機上的功能。如果您想了解更多關於此功能的資訊,請開啟一個終端應用程式並鍵入man convert(這應該適用於 Mac OS 和 Linux)。
  • 您可以開啟 Stata 並執行程式。
  • 您可以從 R 執行 pdflatex,並直接在 pdf 瀏覽器中開啟 pdf。
system("convert W:/toto.ps W:/toto.png") # converts toto.ps to toto.png
system("D:/Stata10/stata.exe do D:/pgm.do", wait = F) # opens Stata and run pgm.do
system("pdflatex.exe -shell-escape file.tex") # runs pdflatex
system("open file.pdf") # opens the pdf
system("open M:/.../doc/*.pdf") # opens all the pdf in a directory

另見sys()Hmisc 包中,shell()shell.exec().

檔案處理

[編輯 | 編輯原始碼]

dir()列出目錄中的所有檔案。它類似於 Unix 函式ls. dir.create() 建立一個新目錄。它類似於mkdir在 Unix 中。

file.info()提供有關檔案的資訊。

> file.info("taille.txt")
           size isdir mode               mtime               ctime               atime exe
taille.txt  444 FALSE  666 2009-06-26 12:25:44 2009-06-26 12:25:43 2009-06-26 12:25:43  no

刪除具有特定模式的檔案 

file.remove(dir(path="directoryname", pattern="*.log"))
  • file.edit() 在文字編輯器中開啟檔案。
  • file.show()在新視窗中開啟檔案。
  • tempfile()建立一個臨時檔案。
  • getZip()在 Hmisc 包中。

網際網路

[編輯 | 編輯原始碼]

browseURL()使用網際網路瀏覽器開啟 URL。download.file()從網際網路下載檔案。

> browseURL("https://wikibook.tw/wiki/R_Programming")

要檢視預設瀏覽器,請使用getOption()

getOption("browser")

我們可以使用以下命令更改預設瀏覽器options()命令。最好先儲存選項。

oldoptions <- options() # save the options
options(browser = "D:/FramafoxPortable/FramafoxPortable.exe")

您可以使用 download.file() 從網際網路下載檔案。請注意,您通常不需要從網際網路下載檔案,您可以直接使用標準函式從網際網路將檔案載入到 R 中。例如,如果您想從網際網路讀取文字檔案,可以使用 read.table()scan()readLines()

# For example, we download "https://wikibook.tw/wiki/R_Programming/Text_Processing" on our Desktop
download.file(url="https://wikibook.tw/wiki/R_Programming/Text_Processing",destfile= "~/Desktop/test_processing.html")
# You can also read it into R using readLines()
text <- readLines("https://wikibook.tw/wiki/R_Programming/Text_Processing")

另見 RCurl

計算時間

[編輯 | 編輯原始碼]

如果您執行計算機密集型任務,您可能希望最佳化計算時間。有兩個可用的函式:system.time() 和 proc.time()。兩者都返回一個值向量。第一個是標準的 CPU 時間

> system.time(x<-rnorm(10^6))
[1] 1.14 0.07 1.83 0.00 0.00
> debut <- proc.time()
> x <- rnorm(10^6)
> proc.time()-debut
[1]  1.66  0.10 10.32  0.00  0.00

計算過程

[編輯 | 編輯原始碼]

user.prompt()(Zelig) 在計算過程中暫停(如果您想進行演示,這很有用)。waitReturn()(cwhmisc) 執行相同的工作。Sys.sleep()停止計算幾秒鐘。

> user.prompt()

Press <return> to continue: 
> Sys.sleep(5)

如果邏輯條件不成立,則可以使用以下命令停止計算過程stopifnot().

  • trCopy()(TinnR 包) 將物件複製到剪貼簿。如果您想將大型物件複製到剪貼簿,這很有用。例如,如果您想複製函式的程式碼並將其貼上到文字編輯器中。
> trCopy(lm)
[1] TRUE
  • sessionInfo()提供有關當前會話資訊的詳細資訊(R 版本 + 載入的包)。此函式可能對可重複的計算很有用。getRversion()提供當前 R 版本。R.version提供有關計算機的更多詳細資訊,以及R.Version()以列表形式返回相同的資訊。
  • 參見 R.utils[1]

參考文獻

[編輯 | 編輯原始碼]
  1. Henrik Bengtsson (2009). R.utils: 各種程式設計工具。R 包版本 1.1.7。 http://CRAN.R-project.org/package=R.utils
華夏公益教科書