R語言學(xué)習(xí)代碼格式一鍵美化
當(dāng)寫R代碼時(shí),很多時(shí)候?qū)懙拇a或者看到的代碼縮進(jìn)都很難統(tǒng)一到標(biāo)準(zhǔn)的格式。這時(shí)為了規(guī)范化代碼,我們需要再代碼中一行一行查代碼,將其修改成標(biāo)準(zhǔn)的格式。
那么我們有沒有一鍵代碼整理的方式或者R包呢?
答案是有的!
下面我們介紹兩種方法。
RStudio 快捷操作
如果你使用的是RStudio 寫代碼的話,那么只用全選代碼(Ctrl + A),而后輸入如下命令:
Ctrl + Shift + A
即可簡單調(diào)整縮進(jìn)與格式。
但這樣的操作知識對現(xiàn)有代碼的微調(diào),不能將代碼中的=統(tǒng)一成<-,也不能將函數(shù)或者循環(huán)后面的大括號{ }換行或者空格。同樣也不能很好的完美調(diào)整縮進(jìn)。
這時(shí)我們推薦另一個(gè)神器,謝益輝大神的 formatR 包。
formatR 包
我們只需使用如下代碼,就可以對路徑中的代碼一鍵美化:
library(formatR)
# tidy_source("file path")
tidy_source("C:/Users/PC_name/Desktop/myfile.R")
如果添加參數(shù)arrow = T,就可將等號=替換成復(fù)制號<-;
file = "C:/Users/PC_name/Desktop/myfile.R" 則可直接將原本路徑下的文件替換,變成整理好的代碼。
還有更多功能,可以直接看包內(nèi)的說明:
| Arguments | |
|---|---|
| source | a character string: location of the source code (default to be the clipboard; this means we can copy the code to clipboard and use tidy_source() without specifying the argument source) |
| comment | whether to keep comments (TRUE by default) |
| blank | whether to keep blank lines (TRUE by default) |
| arrow | whether to replace the assign operator = with <- |
| brace.newline | whether to put the left brace { to a new line (default FALSE) |
| indent | number of spaces to indent the code (default 4) |
| wrap | whether to wrap comments to the linewidth determined by width.cutoff (note that roxygen comments will never be wrapped) |
| output | output to the console or a file using cat? |
| text | an alternative way to specify the input: if it is NULL, the function will read the source code from the source argument; alternatively, if text is a character vector containing the source code, it will be used as the input and the source argument will be ignored |
| width.cutoff | passed to deparse: integer in [20, 500] determining the cutoff at which line-breaking is tried (default to be getOption(“width”)) |
| … | other arguments passed to cat, e.g. file (this can be useful for batch-processing R scripts, e.g. tidy_source(source = ‘input.R', file = ‘output.R')) |
配合 Shiny 包使用
如果你還是覺得這些參數(shù)太復(fù)雜了,就想要無腦靠無腦點(diǎn)擊鼠標(biāo)就能完成代碼美化工作,那么可以事先安裝好 Shiny 包,而后使用如下代碼,利用交互界面進(jìn)行代碼美化工作。
library(shiny) tidy_app()
下面是一個(gè)例子:
美化前的代碼:

美化后的代碼:

參考
an introduction to this package, with examples and further notes
以上就是R語言學(xué)習(xí)代碼格式一鍵美化的詳細(xì)內(nèi)容,更多關(guān)于R語言代碼格式美化的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
R語言-如何循環(huán)讀取excel并保存為RData
這篇文章主要介紹了R語言循環(huán)讀取excel并保存為RData的操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04
R語言數(shù)據(jù)類型知識點(diǎn)總結(jié)
在本篇文章里小編給大家整理的是一篇關(guān)于R語言數(shù)據(jù)類型知識點(diǎn)總結(jié)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-03-03
使用R中merge()函數(shù)合并數(shù)據(jù)的方法
這篇文章主要介紹了使用R中merge()函數(shù)合并數(shù)據(jù),本文詳細(xì)介紹R中merge()函數(shù)參數(shù)及合并數(shù)據(jù)類型,利用sql的表連接概念進(jìn)行類比,簡單易懂,需要的朋友可以參考下2023-03-03
R語言編程學(xué)習(xí)從Github上安裝包解決網(wǎng)絡(luò)問題
這篇文章主要為大家介紹了R語言編程從Github上安裝包的過程詳解,這樣可以解決很多網(wǎng)絡(luò)問題,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11

