如何用R语言学习代码格式进行一键美化


如何用R语言学习代码格式进行一键美化,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

当写R代码时,很多时候写的代码或者看到的代码缩进都很难统一到标准的格式。这时为了规范化代码,我们需要再代码中一行一行查代码,将其修改成标准的格式。

那么我们有没有一键代码整理的方式或者R包呢?

答案是有的!

下面我们介绍两种方法。

RStudio 快捷操作

如果你使用的是RStudio 写代码的话,那么只用全选代码(Ctrl + A),而后输入如下命令:

Ctrl + Shift + A

即可简单调整缩进与格式。

但这样的操作知识对现有代码的微调,不能将代码中的=统一成<-,也不能将函数或者循环后面的大括号{ }换行或者空格。同样也不能很好的完美调整缩进。

这时我们推荐另一个神器,谢益辉大神的 formatR 包。

formatR 包

我们只需使用如下代码,就可以对路径中的代码一键美化:

library(formatR)# tidy_source("file path")tidy_source("C:/Users/PC_name/Desktop/myfile.R")

如果添加参数arrow = T,就可将等号=替换成复制号<-

file = "C:/Users/PC_name/Desktop/myfile.R" 则可直接将原本路径下的文件替换,变成整理好的代码。

还有更多功能,可以直接看包内的说明:

<tdment
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)
whether to keepments (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 wrapments to the linewidth determined by width.cutoff (note that roxygenments 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 包使用

如果你还是觉得这些参数太复杂了,就想要无脑靠无脑点击鼠标就能完成代码美化工作,那么可以事先安装好 Shiny 包,而后使用如下代码,利用交互界面进行代码美化工作。

library(shiny)tidy_app()

下面是一个例子:

美化前的代码:

美化后的代码:

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注主机评测网行业资讯频道,感谢您对主机评测网的支持。


上一篇:javascript语言能干什么

下一篇:分析PyMySQL获取一条数据会让内存爆炸的原因


Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器