如何用R语言学习代码格式进行一键美化(r语言,开发技术)

时间:2024-04-29 22:21:37 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

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

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

答案是有的!

下面我们介绍两种方法。

RStudio 快捷操作

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

Ctrl + Shift + A

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

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

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

formatR 包

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

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

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

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

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

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 ignoredwidth.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()

下面是一个例子:

美化前的代码:

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

美化后的代码:

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

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:如何用R语言学习代码格式进行一键美化的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:html5中怎么使用canvas实现简单连线动画下一篇:

13 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18