加入收藏 | 设为首页 | 会员中心 | 我要投稿 站长网 (https://www.86zz.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

R语言教学代码格式一键美化

发布时间:2021-11-07 16:23:29 所属栏目:教程 来源:互联网
导读:目录 RStudio 快捷操作formatR 包配合 Shiny 包使用参考 当写R代码时,很多时候写的代码或者看到的代码缩进都很难统一到标准的格式。这时为了规范化代码,我们需要再代码中一行一行查代码,将其修改成标准的格式。 那么我们有没有一键代码整理的方式或者R包呢
目录
RStudio 快捷操作formatR 包配合 Shiny 包使用参考
当写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" 则可直接将原本路径下的文件替换,变成整理好的代码。
 
还有更多功能,可以直接看包内的说明:
 
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'))

(编辑:站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读