RStudio 及其 API 学习笔记
2020-09-14
1 两个主要快捷键
两个最主要的快捷键(Sprycha 2019)
- Alt + (-) for inserting assignment operator
<-
- Ctrl + Shift + M for a magrittr operator (aka pipe)
%>%
2 Snippets
You can edit these files directly to customize snippet definitions or you can use the Edit Snippets dialog as described above. If you need to move custom snippet definitions to another system then simply place them in ~/.R/snippets and they’ll be used in preference to the built-in snippet definitions. https://support.rstudio.com/hc/en-us/articles/204463668-Code-Snippets
snippets 一些很有用的 快捷键
如
键入 lib
,按 shift + tab,可以快速弹出 library(package)
snippet lib
library(${1:package})
snippet req
require(${1:package})
snippet src
source("${1:file.R}")
snippet ret
return(${1:code})
snippet mat
matrix(${1:data}, nrow = ${2:rows}, ncol = ${3:cols})
snippet sg
setGeneric("${1:generic}", function(${2:x, ...}) {
standardGeneric("${1:generic}")
})
snippet sm
setMethod("${1:generic}", ${2:class}, function(${2:x, ...}) {
${0}
})
snippet sc
setClass("${1:Class}", slots = c(${2:name = "type"}))
snippet if
if (${1:condition}) {
${0}
}
snippet el
else {
${0}
}
snippet ei
else if (${1:condition}) {
${0}
}
snippet fun
${1:name} <- function(${2:variables}) {
${0}
}
snippet for
for (${1:variable} in ${2:vector}) {
${0}
}
snippet while
while (${1:condition}) {
${0}
}
snippet switch
switch (${1:object},
${2:case} = ${3:action}
)
snippet apply
apply(${1:array}, ${2:margin}, ${3:...})
snippet lapply
lapply(${1:list}, ${2:function})
snippet sapply
sapply(${1:list}, ${2:function})
snippet mapply
mapply(${1:function}, ${2:...})
snippet tapply
tapply(${1:vector}, ${2:index}, ${3:function})
snippet vapply
vapply(${1:list}, ${2:function}, FUN.VALUE = ${3:type}, ${4:...})
snippet rapply
rapply(${1:list}, ${2:function})
snippet ts
# Mon Sep 14 13:49:01 2020 ------------------------------
snippet shinyapp
library(shiny)
ui <- fluidPage(
${0}
)
server <- function(input, output, session) {
}
shinyApp(ui, server)
snippet shinymod
${1:name}_UI <- function(id) {
ns <- NS(id)
tagList(
${0}
)
}
${1:name} <- function(input, output, session) {
}
3 移动光标位置
将光标放到文末
4 RStudio Jobs
参考 McPherson (2019)
When you run an R script in RStudio today, the R console waits for it to complete, and you can’t do much with RStudio until the script is finished running.
正是我的痛点,现在 Jobs 这个功能解决了。
同时已经封装到 rstudiapi
包中。
更快的方式是使用函数jobRunScript {rstudioapi}
## Warning: package 'rstudioapi' was built under R version 3.6.3
## function (path, name = NULL, encoding = "unknown", workingDir = NULL,
## importEnv = FALSE, exportEnv = "")
## NULL
此时会直接调用到 Jobs 窗口。
5 加入弹窗
6 Debugging
学习 R 的 debug,更多参考
- What They Forgot to Teach You About R
- jennybc/whattheyforgot: What They Forgot To Teach You About R, homepage for “how to’s” and workshops
6.1 介绍
参考 jozef R 代码执行过程中,会产生报错是很正常的情况,但是如果报错是产生于一个调用的函数,问题就会变得复杂,因此找到函数内对应的哪一条有问题,就可以促进问题的解决,下面是一些常用的方式。
对于任何一个报错的函数,假设为 order
,输入
执行以后,再执行 order(10:1)
等,就会进入 debugging 界面,10:1
是函数的输入。
在 Win7 系统上,键入 F10,代码就会一行行进行,直到出现报错,这样就能定位报错具体在哪一行。 同在在过程中,可以对任何中间变量进行 print,方便查看中间变量的各种特性。
最后测试完后,输入
order
函数会恢复正常。
6.2 实例
在做面板数据模型时,常用到 plm 包,但是这个包不是 host 在 GitHub 上的,因此不方便跟作者进行交流,因此自己在 GitHub 上的镜像 clone 了源代码,进行修改。 目前项目见 https://github.com/JiaxiangBU/plm。
在进行 plm 模型训练时,产生了报错,
而且是底层错误,跟 plm 包无关,进行 debug 后,发现原因是 x
和 Between(x, "individual", ...)
之间的 index 不一致,虽然两者的 length 都相同,那么只要使用 as.numeric
进行清洗,就可以正常加减或者利用广播机制了。
具体见 commit。
下面是具体思路
->
->
->
->
->
Browse[8]> length(x)
[1] 382
Browse[8]> length(Between(x, "individual", ...))
[1] 382
Browse[8]> x - Between(x, "individual", ...)
Error: Can't join on '.rows' x '.rows' because of incompatible types (list / list)
对象长度一致,但是不能匹配。
->
rowse[8]> class(x);class(Between(x, "individual", ...))
[1] "pseries" "numeric"
[1] "pseries" "numeric"
对象类型一致,但是不能匹配。
Browse[8]> class(x);class(Between(x, "individual", ...))
[1] "pseries" "numeric"
[1] "pseries" "numeric"
->
6.3 建立 breakpoints
Editor Breakpoints can be added in RStudio by clicking to the left of the line in RStudio or pressing Shift+F9 with the cursor on your line. A breakpoint is same as browser() but it doesn’t involve changing codes. Breakpoints are denoted by a red circle on the left side, indicating that debug mode will be entered at this line after the source is run. (dhruv5819 2020)
进入 debugging 状态有多种方式
- 对于一个 R Script,点击左侧的产生红点
- 选中行,快捷键 Shift + F9,再次按取消。
- 在对应的地方,插入
browser()
参考 support
In order to enter debug mode, you’ll need to tell R when you want to pause the computation. R doesn’t have a “pause now” feature (and most computations are so fast that such a feature would not be helpful!). Instead, you’ll want to “set your traps” prior to starting your computation.
设计好browser()
后,按 shift + F5
> debug(print_sth)<kbd></kbd>
> print_sth()
debugging in: print_sth()
debug at #1: {
print(1:10)
print(1:10)
browser()
print(1:10)
}
Browse[2]> c
[1] 1 2 3 4 5 6 7 8 9 10
[1] 1 2 3 4 5 6 7 8 9 10
Called from: print_sth()
这样就避免了,一次次按 F10 等待
- ls(): Objects available in current environment.
- print(): To evaluate objects.
- n: To examine the next statement.
- s: To examine the next statement by stepping into function calls.
- where: To print a stack trace.
- c: To leave debugger and continue with execution.
- C: To exit debugger and go back to R prompt.
这些命令可以具体查询在browser[1]>
状态,环境的情况。
6.4 debug once
参考 support
## [1] 1 2 3 4 5 6 7 8 9 10
## [1] 1 2 3 4 5 6 7 8 9 10
## [1] 1 2 3 4 5 6 7 8 9 10
## [1] 1 2 3 4 5 6 7 8 9 10
## [1] 1 2 3 4 5 6 7 8 9 10
## [1] 1 2 3 4 5 6 7 8 9 10
debugonce
只会有效一次,这样方便,有时候 debug
后找不到函数,没法undebug
。
debugonce 应该查看报错对应的函数进行,这样节省时间,加入 debugonce 的内容。
6.5 退出 debug 状态
debuggingState(on=FALSE)
退出 debug 状态 Stack Overflow
6.6 traceback
The
traceback()
function is used to give all the information on how your function arrived at an error. It will display all the functions called before the error arrived called the “call stack” in many languages, R favors calling traceback. (dhruv5819 2020)
当产生报错时,可以知道函数之间嵌套的关系,方便追溯报错。
7 rstudioapi insertText
rstudioapi::insertText
插入文本,这是一个非常基础的函数,可以在当前页面中插入文本,目前是
add2pkg 开发的基础。
例如制作 addins
但是这里需要注意插入的行数,如
这里只能默认是1行,非4行,这里好好想想。 解决了 https://github.com/JiaxiangBU/add2md/commit/709ea7db743713d96cda419c7fb215633170358e
8 Pane 快捷方式
8.1 Pane 快捷键提示位置
8.2 全屏 source 框
ctrl + shift + 1
8.3 全屏 console 框
ctrl + shift + 2
8.4 恢复四个框
ctrl+shift+alt+0
9 go to line …
- Mac: shift + alt + cmd + G
- Win7: shift + alt + G
10 打开网页
rstudioapi::viewer()
可以打开网页,参考Github Pages
11 改变 RStudio 外观
Tools -> Global Options 打开,就可以修改 theme 了。
12 默认的 global options
参考 https://www.notion.so/Supercharging-RStudio-3d17d0b4642f43cb871227460d7b74b7
- Save workspace to .RData on exit: Never
- Show Indent guides: Yes
- Ensure that source files end with newline
- Strip trailing horizontal whitespace when saving
- Enable SpellCheck
13 How to quit Python in RStudio IDE
Both fail.
参考 https://community.rstudio.com/t/how-to-quit-python-in-rstudio-ide/51890/2?u=econkid
If I remember correctly, Python quits with exit (not exit()), so maybe try that instead.
14 执行 Python 脚本
我发现可以直接根据 Python 脚本,在 RStudio 里面跑! 打开 python 脚本,ctrl + enter 执行后,进入 console。
15 Reopen RStudio
## function (message = "Initial commit")
## {
## needs_init <- !uses_git()
## if (needs_init) {
## ui_done("Initialising Git repo")
## git_init()
## }
## use_git_ignore(c(".Rhistory", ".RData", ".Rproj.user"))
## if (git_uncommitted(untracked = TRUE)) {
## git_ask_commit(message, untracked = TRUE)
## }
## if (needs_init) {
## restart_rstudio("A restart of RStudio is required to activate the Git pane")
## }
## invisible(TRUE)
## }
## <bytecode: 0x0000000012608c90>
## <environment: namespace:usethis>
参考
https://github.com/r-lib/usethis/blob/f5eb0e3240a50a9d757e1825b860475decae6dbf/R/rstudio.R#L149-L171
https://github.com/r-lib/usethis/blob/f5eb0e3240a50a9d757e1825b860475decae6dbf/R/rstudio.R#L170
rstudioapi::openProject(proj_get())
重新打开。
16 命令行打开 RStudio 项目
17 ERROR: option error has NULL value
That’s a known issue . Try installing a build version of RStudio form here . RStudio 1.2.1568 solved the problem for me on macOS 10.14.6. https://community.rstudio.com/t/error-option-error-has-null-value/37605/2
安装新版本,在用 Rmd 写 Python 发现的问题。
参考 https://rstudio.com/products/rstudio/older-versions/ 目前能安装 RStudio-1.2.5042.exe
18 Git Bash in RStudio uncolored.
https://community.rstudio.com/t/git-bash-in-rstudio-uncolored/78570
然后就进入 color 版本了。
dhruv5819. 2020. “Debugging in R Programming.” GeeksforGeeks. 2020. https://www.geeksforgeeks.org/debugging-in-r-programming/.
McPherson, Jonathan. 2019. “RStudio 1.2 Preview: Jobs.” RStudio, Inc. 2019. https://blog.rstudio.com/2019/03/14/rstudio-1-2-jobs/.
Sprycha, Krzysztof. 2019. “R Studio Shortcuts and Tips – Part 2.” appsilon.com. 2019. https://appsilon.com/r-studio-shortcuts-and-tips-part-2/.