您好,登錄后才能下訂單哦!
如何用R語言學(xué)習(xí)代碼格式進(jìn)行一鍵美化,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(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
寫代碼的話,那么只用全選代碼(Ctrl + A
),而后輸入如下命令:
Ctrl + Shift + A
即可簡(jiǎn)單調(diào)整縮進(jìn)與格式。
但這樣的操作知識(shí)對(duì)現(xiàn)有代碼的微調(diào),不能將代碼中的=
統(tǒng)一成<-
,也不能將函數(shù)或者循環(huán)后面的大括號(hào){ }
換行或者空格。同樣也不能很好的完美調(diào)整縮進(jìn)。
這時(shí)我們推薦另一個(gè)神器,謝益輝大神的 formatR
包。
我們只需使用如下代碼,就可以對(duì)路徑中的代碼一鍵美化:
library(formatR) # tidy_source("file path") tidy_source("C:/Users/PC_name/Desktop/myfile.R")
如果添加參數(shù)arrow = T
,就可將等號(hào)=
替換成復(fù)制號(hào)<-
;
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')) |
如果你還是覺得這些參數(shù)太復(fù)雜了,就想要無腦靠無腦點(diǎn)擊鼠標(biāo)就能完成代碼美化工作,那么可以事先安裝好 Shiny
包,而后使用如下代碼,利用交互界面進(jìn)行代碼美化工作。
library(shiny) tidy_app()
下面是一個(gè)例子:
美化前的代碼:
美化后的代碼:
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。