更新:2018年6月22日
感谢@Lorenz@kirill@yuhi提供的styler
包。我已使用它一段时间了。安装完包后最简单的方法是只需使用
滚动到Addin-->样式活动文件
通过界面进行的自定义选项可以控制我们喜欢的样式。
Rstudio现在可以格式化代码,使其看起来整洁。选择感兴趣的行,然后导航到Code
>>重新格式化代码
或使用键盘快捷键Ctrl+Shift+A。
或者只需运行样式目录命令以对目录中的所有文件进行样式处理。
styler::style_dir()
更新:
这是重构代码的好方法,但是对于向量元素中的,
它会出现问题。如果向向量传递了许多元素,那么这样做就过度了:
x <- c(
"p.G12C",
"p.F121S",
"p.P124S",
"p.P124L",
"p.E13D",
"p.E203K",
"p.Q209P",
"p.Q209P",
"p.Q209L"
)
更新:R-Studio版本0.99.893
由于R-Studio的Addins
中新增了一个功能,现在你可以添加@yuhi formatR作为Addin。这比内置的code >> Refromat code
更整洁和清晰地结构化代码。但是,使用Addin Reformat R Code
的缺点是它会对Rshiny代码产生错误。
先按下CTRL+A,再按下CTRL+SHIFT+A。
若使用Mac电脑,请改用⌘键替代CTRL键。
进入 Code
菜单并选择
重新缩进行
在我的操作系统下,快捷键为 Ctrl + I。
这个包 styler 可以格式化R代码,你可以通过RStudio插件访问它,以格式化活动文件、突出显示的代码、包等。一个与众不同的特点是,按照样式指南转换代码是分开完成的,这使得按任意样式指南进行样式设置成为可能。从1.2.0版本开始,插件也是如此。
我们实现了tidyverse样式指南,同时允许在样式设置方面有一定的灵活性。此外,管道,tidyeval语法等也可以正确处理。您可以在博客文章中阅读介绍。
如果您不想遵循tidyverse样式指南,可以查看vignette '自定义Styler',其中描述了如何实现任意样式指南。在这个vignette中,我展示了如何实现一个由一个规则组成的样式指南:在{
之前始终换行。希望对你有所帮助。
声明:我是styler的管理员。
除了之前给出的绝妙答案,您还可以使用styler
包和shrtcts包来启用保存时格式化,这是RStudio官方仍未支持的功能。
Use the command shrtcts::edit_shortcuts()
in the RStudio Console to open the file where you define your custom shortcuts.
Paste the following code inside that file (set your preferred keybinding in the @shortcut
line).
#' Format on Save
#'
#' @description
#' Format Document with styler Package and Save Document.
#' @interactive
#' @shortcut Cmd+S
function() {
# format only .R and .Rmd files, but save all file types
file_type <- tools::file_ext(rstudioapi::getActiveDocumentContext()$path)
if (file_type %in% c("R", "Rmd", "qmd")) {
styler:::style_active_file() |>
capture.output() |>
invisible()
}
rstudioapi::documentSave() |>
capture.output() |>
invisible()
}
This solution uses the native pipe |>
and thus requires R 4.1
.
You can of course just define separate variables in each line or use the magrittr
pipe if you use earlier versions of R
.
Use the command shrtcts::add_rstudio_shortcuts(set_keyboard_shortcuts = TRUE)
in the RStudio Console to add the new shortcut with its assigned keybinding. Then restart RStudio.
Cmd+S
时,将使用styler
软件包对当前活动的.R
或.Rmd
文档进行格式化,并保存格式化的版本。
所有其他类型的文件都将在不进行格式化的情况下保存,但您可以轻松地使用一个包来扩展上述代码,以便格式化例如.md
或.py
文件。Untitled
文件或当前的R
会话忙碌时,该方法将无法工作。cmd+S
而不是 Ctrl+S
,花了我一些时间才弄清楚为什么它不能工作。非常感谢。 - Björn