溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何用R語言學(xué)習(xí)代碼格式進(jìn)行一鍵美化

發(fā)布時(shí)間:2021-11-05 13:39:02 來源:億速云 閱讀:358 作者:柒染 欄目:開發(fā)技術(shù)

如何用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 快捷操作

如果你使用的是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 包。

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
sourcea 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)
commentwhether to keep comments (TRUE by default)
blankwhether to keep blank lines (TRUE by default)
arrowwhether to replace the assign operator = with <-
brace.newlinewhether to put the left brace { to a new line (default FALSE)
indentnumber of spaces to indent the code (default 4)
wrapwhether to wrap comments to the linewidth determined by width.cutoff (note that roxygen comments will never be wrapped)
outputoutput to the console or a file using cat?
textan 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.cutoffpassed 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è)例子:

美化前的代碼:

如何用R語言學(xué)習(xí)代碼格式進(jìn)行一鍵美化

美化后的代碼:

如何用R語言學(xué)習(xí)代碼格式進(jìn)行一鍵美化

看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。

向AI問一下細(xì)節(jié)

免責(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)容。

AI