Rstudio: Difference between revisions

From 太極
Jump to navigation Jump to search
(122 intermediate revisions by the same user not shown)
Line 1: Line 1:
= Different tastes =
= Different tastes =
== Server ==
== Server ==
Like the Cloud version (a little better than the cloud version), the connection is unstable:(
* https://posit.co/download/rstudio-server/
* [https://support.posit.co/hc/en-us/articles/200532327-Managing-RStudio-Workbench-RStudio-Server Managing RStudio Workbench / RStudio Server]
* [https://stackoverflow.com/a/21999837 R - Character set is not UTF-8; please change your locale]. Run '''dpkg-reconfigure locales''' and enable '''en_US-UTF-8'''


So '''it is unusable'''.
=== Docker ===
* This is useful if RStudio desktop is not available for your Linux distribution. Another choice is '''Singularity''' if we don't have sudo privilege.
* [https://towardsdatascience.com/running-rstudio-inside-a-container-e9db5e809ff8 Running RStudio Inside a Container]


== Cloud ==
== Cloud ==
Line 19: Line 23:


I got an error "Error occurred during transmission" when I try to run an R statement.
I got an error "Error occurred during transmission" when I try to run an R statement.
[https://blog.rstudio.com/2021/09/28/what-s-new-on-rstudio-cloud-september-2021/ What's New on RStudio Cloud - September 2021]


== Desktop ==
== Desktop ==
'''Build from source'''
'''Build from source'''
See https://github.com/rstudio/rstudio/blob/master/INSTALL for installation instruction.
See <s>https://github.com/rstudio/rstudio/blob/master/INSTALL</s> https://github.com/rstudio/rstudio/blob/main/INSTALL for installation instruction.
 
{{Pre}}
sudo apt-get install git cmake build-essential libboost-all-dev libssl-dev libbz2-dev libpam-dev libxslt1-dev libsqlite3-dev libpq-dev libmysqlclient-dev pandoc libcurl4-openssl-dev libxml2-dev libxslt1-dev zlib1g-dev libreadline-dev libpcre3-dev liblzma-dev libblas-dev libatlas-base-dev liblapack-dev libapparmor-dev libedit2 libobjc4 openjdk-11-jdk
 
git clone https://github.com/rstudio/rstudio.git


To build Rstudio from source in Ubuntu:
cd rstudio
mkdir build
cd build
cmake .. -DRSTUDIO_TARGET=Desktop -DCMAKE_BUILD_TYPE=Release
sudo make install
</pre>
 
(2023) [https://github.com/rstudio/rstudio/wiki/Electron-Desktop Electron Desktop]. The Electron desktop (under development) replaces QtWebEngine with Electron. The sources live in src/node/desktop; it is written primarily in TypeScript.
 
To build Rstudio from source in Ubuntu (outdated):
* Install R.
* Install R.
* Install Qt 4.
* Install Qt 4.
Line 64: Line 84:


= Releases =
= Releases =
* https://dailies.rstudio.com/release/
* [https://blog.rstudio.com/2021/06/09/rstudio-v1-4-update-whats-new/ RStudio v1.4 Update: What's New] - R 4.1 Support, 2021-06-09
* [https://www.rstudio.com/products/rstudio/download/preview/?s=09 RStudio v1.4.1714-2 Preview]. Support for the upcoming R 4.1.0 release, including the new |> pipe, \(x) function shorthand, and new graphics engine.
* [https://blog.rstudio.com/2020/09/30/rstudio-v1-4-preview-visual-markdown-editing/ RStudio v1.4 Preview: Visual Markdown Editing], [https://blog.rstudio.com/2020/10/07/rstudio-v1-4-preview-python-support/ Python Support], [https://blog.rstudio.com/2020/10/14/rstudio-v1-4-preview-command-palette/?s=09 Command Palette], [https://blog.rstudio.com/2020/11/09/rstudio-1-4-preview-citations/ Citations], [https://blog.rstudio.com/2020/12/02/rstudio-v1-4-preview-little-things/ The Little Things]
* [https://blog.rstudio.com/2020/02/25/rstudio-1-3-integrated-tutorials/ RStudio 1.3 Preview: Integrated Tutorials]: learnr package. [https://blog.rstudio.com/2019/12/02/learnr-0-10-0/ learnr 0.10.0].
* [https://blog.rstudio.com/2020/02/25/rstudio-1-3-integrated-tutorials/ RStudio 1.3 Preview: Integrated Tutorials]: learnr package. [https://blog.rstudio.com/2019/12/02/learnr-0-10-0/ learnr 0.10.0].
* [https://blog.rstudio.com/2019/04/30/rstudio-1-2-release/ 1.2]
* [https://blog.rstudio.com/2019/04/30/rstudio-1-2-release/ 1.2]
Line 72: Line 96:


= Preferences =
= Preferences =
== rstudio.prefs ==
[https://twitter.com/sharon000/status/1458798530294951947 rstudio.prefs] package, on [https://cran.rstudio.com/web/packages/rstudio.prefs/index.html CRAN]
== Configuration file ==
'''~/.config/rstudio/rstudio-prefs.json''' (checked in Linux & macOS).
Note: the file exists under each project folder. However if I modify the file by adding an editor theme like '''"editor_theme": "Xcode"''' for project-specific, it won't be taken.
[https://community.rstudio.com/t/where-else-rstudio-searches-for-rstudio-prefs-json/95349 Where else RStudio searches for rstudio-prefs.json?] ''Currently, only a small handful of RStudio preferences can be set on a project (not global) level. ''
== RStudio Theme ==
== RStudio Theme ==
Background color (v1.1.383, see an animation on [https://community.rstudio.com/t/rstudio-theme-modern-vs-sky/1879 this post])
Background color (v1.1.383, see an animation on [https://community.rstudio.com/t/rstudio-theme-modern-vs-sky/1879 this post])
Line 87: Line 121:


== Editor theme ==
== Editor theme ==
I pick "Vibrant Ink".
* [https://support.rstudio.com/hc/en-us/articles/115011846747-Using-Themes-in-the-RStudio-IDE Using Themes in the RStudio IDE]
* [https://docs.posit.co/ide/user/ide/guide/ui/appearance.html Themes] from RStudio User Guide
** '''.ace_selection'''
* '''Vibrant Ink''',
** [[File:Vibrant ink rstheme.png|250px]]
** Advantages: 1) dark background and 2) (more important) they draw rectangles using bright colors around the words we search.
** VS code has a better highlight of search words. In RStudio, it only add a rectangle on the edge but VS code will change the background color of search word.
** https://github.com/captaincaed/rstudio/blob/main/vibrant_ink_SB_2.rstheme. Download the file and open it in RStudio. Change the syntax highlight from Text file to CSS.
** [https://gist.github.com/arraytools/b2f3eed3ae50eb99665b233a81149bc1 My modification]: change the border of rectangles from blue to orange for all matched find words (line 39). After using rstudioapi::addTheme(), the theme file appears in ~/.configrstudio/themes directory. We may open the file in RStudio and experiment the setting. After that, we can call '''rstudioapi::applyTheme("Vibrant Ink SB 2")''' to apply the change. Note the theme name is at the first line of the file.
::<syntaxhighlight lang='css'>
.ace_marker-layer .ace_selected-word {
  border: 1px solid #FF6600
}
</syntaxhighlight>
* [https://r-coder.com/rstudio-themes/#RStudio_dark_themes RStudio themes] from r-coder.com
* [https://www.rstudio.com/blog/rstudio-ide-custom-theme-support/ RStudio IDE Custom Theme Support], [https://towardsdatascience.com/customize-your-rstudio-theme-914cca8b04b1 How to Customize your RStudio Theme (Finally)]. RStudio now lets you upload '''.tmTheme''' and '''.rsTheme''' files.
* [https://github.com/gadenbuie/rsthemes rsthemes] package: Full RStudio IDE and Syntax Themes by gadenbuie
** The package includes several theme files
** It called the function '''rstudioapi::addTheme(theme, force = TRUE)''' to install each of theme files
** On Ubuntu/Mac, these themes are added and saved in '''~/.config/rstudio/themes''' directory. See [https://docs.posit.co/ide/user/ide/guide/ui/appearance.html#testing-changes-to-a-theme Sharing a theme] about the path on Windows.
** To remove a theme, '''rstudioapi::removeTheme("theme-name")'''. The default becomes  TextMate on my macOS.
* [https://github.com/mkearney/rstudiothemes A curated list of RStudio themes found on Github] with gallery, 2019
* [https://github.com/max-alletsee/rstudio-themes RStudio Theme Collection] (updated)


== R markdown ==
== Change selected word highlight color in source - theme ==
[https://stackoverflow.com/a/40570719 Rstudio - How to show plot output in bottom right pane?]
* [https://posit.co/blog/rstudio-ide-custom-theme-support/ RStudio IDE Custom Theme Support]
[https://stackoverflow.com/a/27119882 View markdown generated html in RStudio viewer]
* [https://community.rstudio.com/t/change-selected-word-highlight-color-in-source/4475 Change selected word highlight color in source?]
* [https://community.rstudio.com/t/feature-req-word-background-highlight-color-in-find-and-spellcheck/18578 Feature req: word background highlight color in find and spellcheck]
* [https://www.reddit.com/r/RStudio/comments/jdwrcg/how_to_use_custom_rstudio_themes_and_change_r/ How to: Use custom RStudio themes and change R chunk background color]
* [https://towardsdatascience.com/customize-your-rstudio-theme-914cca8b04b1 How to Customize your RStudio Theme (Finally)]
* [https://community.rstudio.com/t/change-code-highlight-colours-when-double-clicking-on-a-word/96122/3 Change code highlight colours when double clicking on a word] 2021/2
 
== R markdown, inline output for plots ==
<ul>
<li>[https://stackoverflow.com/questions/38068774/rstudio-suddenly-stopped-showing-plots-in-the-plot-pane RStudio suddenly stopped showing plots in the plot pane]
* Method 1: dev.off(); plot(1)
* Method 2: RStudio - Preferences. Go to Tools->Global Options->Rmarkdown. In "Show output preview in" select "Viewer Pane" (default is "Window"). Uncheck the box "Show output inline for all R Markdown documents".
 
<li>[https://stackoverflow.com/a/40570719 Rstudio - How to show plot output in bottom right pane?]
<li>[https://stackoverflow.com/a/27119882 View markdown generated html in RStudio viewer]
<li>[https://www.rstudio.com/blog/r-markdown-tips-tricks-1-rstudio-ide/ Show plots in the Viewer pane]. By default, code chunks display R Markdown plots “inline”, or directly underneath the code chunk. <BR/>
[[File:Rstudiormarkdown.png|200px]]
<li>[https://stackoverflow.com/a/42965478 Prevent Rstudio from displaying plots in the source panel]. This is a new feature in notebook. To get rid of this, on the source panel, there is a little setting icon, choose that and select "Chunk Output in console". It seems the default is "Chunk Output inline".
<li>[https://bookdown.org/yihui/rmarkdown-cookbook/figure-size.html 5.4 Control the size of plots/images]. It seems the '''height''' parameter is not working when I try the '''markdown syntax''' method in the '''Source''' mode (cf Visual mode).
</ul>
 
== tab and spaces ==
Options -> Code -> Editing. Tab width is 2 by default.
 
Wish there is an option for this depending on the language. For example some C code uses 4 spaces as tab.
 
== Mouse Cursor ==
* [https://github.com/rstudio/rstudio/issues/2685 Cursor extremely difficult to see on dark theme #2685]
* [https://stackoverflow.com/questions/40941467/r-studio-change-cursor-color R Studio: Change cursor color]
* [https://github.com/rstudio/rstudio/issues/8781 "Hand pointer" mouse cursor in RStudio does not follow system theme and it is much smaller than normal size #8781]


= Toolbar =
= Toolbar =
View -> Hide Toolbar
View -> Hide Toolbar
= RStudio Package Manager =
* https://docs.rstudio.com/rspm/admin/index.html
* [https://resources.rstudio.com/webinars/introduction-to-the-rstudio-package-manager-sean-lopp Introduction to the RStudio Package Manager] - Sean Lopp
* [https://support.rstudio.com/hc/en-us/articles/360009982613-How-do-I-update-packages-in-RStudio-Package-Manager- How do I update packages in RStudio Package Manager?]
* [https://blog.rstudio.com/2020/12/07/package-manager-1-2-0/ RStudio Package Manager 1.2.0 - Bioconductor & PyPI]
* [https://packagemanager.rstudio.com/client/#/ RStudio Public Package Manager]
** [https://support.rstudio.com/hc/en-us/articles/360046703913-FAQ-for-Public-RStudio-Package-Manager FAQ for Public RStudio Package Manager]
* [https://tshafer.com/blog/2023/07/posit-package-manager-linux Posit Package Manager for Linux R Binaries] 2023/7/29


= Change repository =
= Change repository =
Line 130: Line 224:


= Change R version =
= Change R version =
[https://docs.posit.co/resources/install-r-source/ Install R from Source] from Posit Documentation.
== Desktop ==
== Desktop ==
https://support.rstudio.com/hc/en-us/articles/200486138-Changing-R-versions-for-RStudio-desktop
https://support.rstudio.com/hc/en-us/articles/200486138-Changing-R-versions-for-RStudio-desktop
Line 158: Line 253:


= Get help on firefox/chrome browser =
= Get help on firefox/chrome browser =
(The help panel is kind of small)
(The help panel is kind of small). If we want to do a search, we can only do that with the small window. We can't do a search if we open the help in a new window.


No, it can't. But alternatively, if we click "Show in a new window" icon, it will bring the help on an independent window.
No, it can't. But alternatively, if we click "Show in a new window" icon, it will bring the help on an independent window.
Line 172: Line 267:


= Tips =
= Tips =
[https://appsilon.com/r-studio-shortcuts-and-tips/ R Studio Shortcuts and Tips]
* [https://youtu.be/kuSQgswZdr8 RStudio Tips and Tricks] 2017 (video)
* [https://appsilon.com/r-studio-shortcuts-and-tips/ R Studio Shortcuts and Tips]
* [https://www.dataquest.io/blog/rstudio-tips-tricks-shortcuts/ 23 RStudio Tips, Tricks, and Shortcuts]
 
== Freeze ==
* [https://community.rstudio.com/t/rstudio-freezing-since-upgrade-to-macos-catalina/59068/5 RStudio freezing since upgrade to macOS Catalina] 2020/3/31 Changing the rendering engine to '''software rendering'''
* [https://community.rstudio.com/t/rstudio-1-4-1106-freezes-on-macos/103695 RStudio 1.4.1106 freezes on macOS] 2021/5/4
* [https://community.rstudio.com/t/rstudio-freezes/60953 RStudio Freezes] 2020/4/12
* [https://support.rstudio.com/hc/en-us/articles/360017886674-Troubleshooting-RStudio-Rendering-Errors Troubleshooting RStudio Rendering Errors]* 2022/5/14
 
== Find in files ==
There is no need to use the "grep" command in a Terminal anymore.
 
* Method 1: '''Ctrl + .''' (aka. Go to File/Function). This will quickly list all files '''in the project''' containing the keyword.
* Method 2: Edit -> '''Find in Files'''. It will open a tab called "Find in Files" after the tabs "Console, Terminal" and before the tab "Background jobs". This will list all files with lines of code containing the keyword in '''the specified folder'''.
 
== Command palette ==
Access it with Ctrl + Shift + P (Windows / Linux) or Cmd + Shift + P (macOS)!
 
== object 'partition_yaml_front_matter' not found ==
[https://community.rstudio.com/t/error-on-opening-rstudio/142022 Error on opening RStudio]. The solution of disabling Prompt to install missing R packages discovered in R source files in the Settings works for me.


== Outline ==
== Outline ==
Line 189: Line 304:


But if I install the package using RStudio's packages panel or through 'menu > Tools > Install Packages...', the package will go to "/Library/Frameworks/R.framework/Versions/3.6/Resources/library". So if we use '''remove.packages()''' without specify the '''lib''' parameter, it may there is no package that can be uninstalled. We can change the installation directory if we install the package using 'menu > Tools > Install Packages...' method. [https://www.accelebrate.com/library/how-to-articles/r-rstudio-library Here] has some screenshots on Windows OS.
But if I install the package using RStudio's packages panel or through 'menu > Tools > Install Packages...', the package will go to "/Library/Frameworks/R.framework/Versions/3.6/Resources/library". So if we use '''remove.packages()''' without specify the '''lib''' parameter, it may there is no package that can be uninstalled. We can change the installation directory if we install the package using 'menu > Tools > Install Packages...' method. [https://www.accelebrate.com/library/how-to-articles/r-rstudio-library Here] has some screenshots on Windows OS.
== Visual Markdown Editor ==
* https://rstudio.github.io/visual-markdown-editing/
* [https://www.rstudio.com/blog/exploring-rstudio-visual-markdown-editor/ Exploring RStudio’s Visual Markdown Editor]
* Video
** [https://youtu.be/CjS90dBrEho rmarkdown: Make PDF Data Analysis Reports with RStudio Visual Editor]
* Message when we switch from source editor to visual editor
:[[File:RStudioVisualMode.png|250px]]
* Note when we switch from source mode to visual mode, RStudio will give us some warning. If we continue, it will modify the source code. Note: even we switch back to the Source mode, it won't undo the code change. If we want to undo the code change, we should do it by ourselves (ctrl+z/Cmd+z).
** YAML will add markdown wrap: 72
** Rmd document will wrap long lines. Itemized lines will be reformatted.
** The response speed in Visual mode is slow. Arrow keys navigation seems not responding.
** Inline images size is increased.
** Outline button/option will be turned on.
* Switch markdown editing mode between Source and Visual
** [https://stackoverflow.com/a/72287229 Switch markdown editing mode between Source and Visual changes special characters]
** '''Canonical Mode''' [https://rstudio.github.io/visual-markdown-editing/markdown.html#canonical-mode Markdown Formats] and [https://rstudio.github.io/visual-markdown-editing/options.html#global-options Options] in project-specific or global.
** My question is after I saved the change in the visual mode, the source code still shows some changes in the file when I switched back to the source mode? The "diff" command shows no difference.
== Drag and drop formulas from Wikipedia into your R Markdown document ==
[https://www.rstudio.com/blog/r-markdown-tips-tricks-1-rstudio-ide/ R Markdown Lesser-Known Tips & Tricks #1: Working in the RStudio IDE]


== [https://stackoverflow.com/questions/31280054/rstudio-can-i-pop-out-the-source-pane Pop out the source pane] to have its own window ==
== [https://stackoverflow.com/questions/31280054/rstudio-can-i-pop-out-the-source-pane Pop out the source pane] to have its own window ==
Line 197: Line 333:
== Column selection ==
== Column selection ==
Click Alt.
Click Alt.
== options(width) ==
Once we resize the width manually with the mouse, the width will be changed at the same time.


== Menu -> Code ==
== Menu -> Code ==
Line 228: Line 367:


[https://apple.stackexchange.com/questions/12993/why-doesnt-bashrc-run-automatically Why doesn't .bashrc run automatically?]
[https://apple.stackexchange.com/questions/12993/why-doesnt-bashrc-run-automatically Why doesn't .bashrc run automatically?]
== Console scroll back ==
https://stackoverflow.com/a/59327459 It is still a problem as of 2021-02-22.


== Snippet ==
== Snippet ==
Line 233: Line 375:
* If you type 'ts' into the console, it should pop up a list. However, the default completion delay is 3 characters, meaning it will not work unless your completion delay is set to 2 characters which you can change in your global options (Code > Completion). This works on R console or an R/Rmd file.
* If you type 'ts' into the console, it should pop up a list. However, the default completion delay is 3 characters, meaning it will not work unless your completion delay is set to 2 characters which you can change in your global options (Code > Completion). This works on R console or an R/Rmd file.
** If you don't want to change your default delay you can just type ts and hit tab.
** If you don't want to change your default delay you can just type ts and hit tab.
* [https://www.infoworld.com/article/3637083/never-look-up-tidyrs-pivotwider-or-pivotlonger-again.html Never look up tidyr’s pivot_wider or pivot_longer again!]


== Crash and log file ==
== Crash and log file ==
On my Mac, the crash report is saved at ~/Library/Logs/DiagnosticReports/rsession_XXXX.crash and the log file is saved at ~/.rstudio-desktop/log/.
On my Mac, the crash report is saved at ~/Library/Logs/DiagnosticReports/rsession_XXXX.crash and the log file is saved at ~/.local/share/rstudio/log/ (From within RStudio: Help Menu -> Diagnostics -> Show Log Files).
 
See also [https://support.rstudio.com/hc/en-us/articles/200554776-RStudio-Crash-Report RStudio Crash Report], [https://support.rstudio.com/hc/en-us/articles/200554756-RStudio-Application-Logs RStudio Application Logs].


From within RStudio: Help Menu -> Diagnostics -> Show Log Files
[[File:RStudioAbort.png|200px]]


See also [https://support.rstudio.com/hc/en-us/articles/200554776-RStudio-Crash-Report RStudio Crash Report], [https://support.rstudio.com/hc/en-us/articles/200554756-RStudio-Application-Logs RStudio Application Logs].
== Open an SVG file from RStudio ==
It only display the file as a text file. It cannot let OS open the file:(


== Check if R is running in RStudio ==
== Check if R is running in RStudio ==
Line 247: Line 393:
.Platform$GUI == "RStudio"
.Platform$GUI == "RStudio"
</pre>
</pre>
= Copilot =
[https://www.youtube.com/watch?v=yVq-b5xHmac GitHub Copilot in Rstudio, it's finally here!]


= Install on Crouton =
= Install on Crouton =
Line 273: Line 422:
</pre>
</pre>
After I run '''sudo apt-get install libjpeg62''', RStudio can be installed successfully.
After I run '''sudo apt-get install libjpeg62''', RStudio can be installed successfully.
= Switch R version for RStudio desktop =
https://support.rstudio.com/hc/en-us/articles/200486138-Changing-R-versions-for-RStudio-desktop
In Linux desktop, we need to run the following (or include the line in '''~/.profile''' file for a permanent solution) before calling 'rstudio' in a terminal.
<syntaxhighlight lang='bash'>
export RSTUDIO_WHICH_R=/opt/R/3.5.0/bin/R
</syntaxhighlight>


= Stop a command =
= Stop a command =
Line 302: Line 443:
** One way it still works is by selecting line(s) first and hitting the key-bind.
** One way it still works is by selecting line(s) first and hitting the key-bind.
** Another way is to go to Tools > Global options > Code. Change to '''Current line''' from the dropdown list next to CMD + Enter executes. The default is "Multiple-line R statements" which should be better since an R statement can spread several lines. The 3rd option "Multiple consecutive R lines" will send a block of R lines automatically which does not look ideal in most cases.
** Another way is to go to Tools > Global options > Code. Change to '''Current line''' from the dropdown list next to CMD + Enter executes. The default is "Multiple-line R statements" which should be better since an R statement can spread several lines. The 3rd option "Multiple consecutive R lines" will send a block of R lines automatically which does not look ideal in most cases.
== Line feed ==
Shift + Enter still works  in RStudio. [https://www.howtogeek.com/825393/shift-enter-is-a-secret-shortcut-everyone-should-know/ Shift+Enter Is a Secret Shortcut Everyone Should Know].


== Move focus to source/console ==
== Move focus to source/console ==
Line 315: Line 459:
* '''Ctrl + Shift + 4''': environment
* '''Ctrl + Shift + 4''': environment
* '''Ctrl + Shift + 0''': show all panes
* '''Ctrl + Shift + 0''': show all panes
== Jump to the matching brackets ==
Ctrl + p


== Show previous/next Plot ==
== Show previous/next Plot ==
Line 331: Line 478:
== View() output ==
== View() output ==
[https://stackoverflow.com/a/30601708 Save View() output of RStudio as html]
[https://stackoverflow.com/a/30601708 Save View() output of RStudio as html]
== Load all when developing a new package ==
The '''ctrl-shift-L''' shortcut which not only unloads/loads the package, but exports all unexported objects, including all pkg data and internal functions. Super handy debugging!


== Automatically reformat code ==
== Automatically reformat code ==
Line 345: Line 495:


= RStudio server =
= RStudio server =
== rsession.conf ==
* [https://community.rstudio.com/t/rstudio-server-timeout-values/76440 rstudio-server timeout values]
* [https://support.rstudio.com/hc/en-us/articles/200552316-Configuring-the-Server RStudio Server: Configuring the Server]
== KVM ==
== KVM ==
[https://chepec.se/2019/01/20/rstudio-server-multiple-instances-kvm/ Multiple Rstudio Server instances using a single R/LaTeX install with KVM]
[https://chepec.se/2019/01/20/rstudio-server-multiple-instances-kvm/ Multiple Rstudio Server instances using a single R/LaTeX install with KVM]


== RStudio Server Installation on Ubuntu ==
== RStudio Server Installation on Ubuntu ==
https://rviews.rstudio.com/2017/06/21/analytics-administration-for-r/
<ul>
<li>https://rviews.rstudio.com/2017/06/21/analytics-administration-for-r/
<li>https://www.rstudio.com/products/rstudio/download-server/debian-ubuntu/
<li>[https://support.rstudio.com/hc/en-us/articles/217027968-Changing-the-system-account-for-RStudio-Workbench-RStudio-Server Changing the system account for RStudio Workbench / RStudio Server]
<li>[http://dirk.eddelbuettel.com/blog/code/r4/ #35: apt install rstudio quarto], https://github.com/eddelbuettel/ppa-rstudio, [https://cran.rstudio.com/bin/linux/ubuntu Install R on Ubuntu]
{{Pre}}
apt update -qq
apt install --no-install-recommends software-properties-common dirmngr
 
wget -qO- https://cloud.r-project.org/bin/linux/ubuntu/marutter_pubkey.asc | sudo tee -a /etc/apt/trusted.gpg.d/cran_ubuntu_key.asc
add-apt-repository "deb https://cloud.r-project.org/bin/linux/ubuntu $(lsb_release -cs)-cran40/"
apt install --no-install-recommends r-base
add-apt-repository ppa:c2d4u.team/c2d4u4.0+
apt install --no-install-recommends r-cran-littler
git clone https://github.com/eddelbuettel/ppa-rstudio.git
cd ppa-rstudio/
./getRStudioServer.r
apt install -f rstudio-server-2022.02.0-438-amd64.deb
 
ps -ef | grep rserver
# http://IP:8787  to acceess
# But what is the username/password?
</pre>
It sounds the docker method is better.
</li>
</ul>


== RStudio Server on Amazon EC2 ==
== RStudio Server on Amazon EC2 ==
* [http://www.slideshare.net/talgalili/rstudio-in-aws-16-9 Setup up Step by Step]
* [http://www.slideshare.net/talgalili/rstudio-in-aws-16-9 Setup up Step by Step]
== 2FA ==
[https://adisarid.github.io/post/2023-05-15-rstudio-server-2fa/rstudio_2fa/ Using OTP (one-time passwords) in rstudio server open source]
== Raspberry Pi ==
* [https://andresrcs.rbind.io/2022/08/22/rstudio_ide_arm/ Take the RStudio IDE experimental support for arm64 architectures out for a spin]
* [https://andresrcs.rbind.io/2021/01/13/raspberry_pi_server/ Automatically installing Shiny and RStudio server on Raspberry Pi OS with Ansible]


= RStudio and Git =
= RStudio and Git =
Line 365: Line 551:
* In order to open another window, use x11(), windows() or quartz() (depending on your device) before each plot. Then call dev.off() to clear last plot. See [https://stackoverflow.com/questions/31008264/how-do-you-delete-the-current-but-not-all-plots-in-the-rstudio-plotting-device How do you delete the current (but not all) plots in the RStudio plotting device?]
* In order to open another window, use x11(), windows() or quartz() (depending on your device) before each plot. Then call dev.off() to clear last plot. See [https://stackoverflow.com/questions/31008264/how-do-you-delete-the-current-but-not-all-plots-in-the-rstudio-plotting-device How do you delete the current (but not all) plots in the RStudio plotting device?]


== Plot does not show up in RStudio's plot window ==
== Where does RStudio save your plots history ==
[https://stackoverflow.com/a/53809715 Save all plots already present in the panel of Rstudio]. In RStudio, every session has a temporary directory that can be obtained using tempdir(). Inside that temporary directory, there is another directory that always starts with "rs-graphics" and contains all the plots saved as ".png" files.
 
== Interactive plots: manipulate ==
[https://support.rstudio.com/hc/en-us/articles/200551906-Interactive-Plotting-with-Manipulate-in-the-RStudio-IDE Interactive Plotting with Manipulate in the RStudio IDE].
 
Sometimes it does not work:(
 
== Plot from Rmd file does not show up in RStudio's plot window ==
<pre>
<pre>
options(device = "RStudioGD") # or dev.off()
options(device = "RStudioGD") # or dev.off()
Line 371: Line 565:
...
...
</pre>
</pre>
[https://community.rstudio.com/t/plot-in-rstudio-not-showing-up/73389 Plot in Rstudio not showing up]
<pre>
> dev.cur()
RStudioGD
        2
</pre>
Note: when I run a ggsurvplot() statement from an Rmd file, the plot is shown in the source panel instead of the plot window. I could not find the plot at first since the chunk is long. dev.cur() returns ''null device'' instead of ''RStudioGD'' after I call ggsurvplot(). It could be an issue with ggsurvplot() since a simple ggplot() call is fine. In this case, I can save ggsurvplot() to an object and print the object will show the plot in the plot window.
== Overlap problem ==
== Overlap problem ==
https://stackoverflow.com/questions/45395220/legends-overlapping-the-plots-in-rstudio
https://stackoverflow.com/questions/45395220/legends-overlapping-the-plots-in-rstudio
Line 377: Line 579:


== Using Projects ==
== Using Projects ==
[https://support.rstudio.com/hc/en-us/articles/200526207-Using-Projects Working with Multiple Projects at Once]
* [https://www.r-bloggers.com/2020/01/rstudio-projects-and-working-directories-a-beginners-guide/ RStudio Projects and Working Directories: A Beginner’s Guide]. Replacing '''setwd()''' by making file paths relative.
** The RStudio project file is a file that sits in the root directory, with the extension .Rproj.
** Everything relating to that analysis or project should only happen within that directory.
** When opening an existing project, you should open the .Rproj file first and only subsequently open any R scripts (extensions with .R) from the RStudio session, rather than going straight to the R scripts to open them.
** '''Structuring your working directory''': Data, Script, Output.
* The folder name will be used to represent a project on the top-right corner of RStudio.
* [https://support.rstudio.com/hc/en-us/articles/200526207-Using-Projects Working with Multiple Projects at Once]
 
== Create an .Rproj file ==
<pre>
mkdir funky
cd funky
echo "Version: 1.0" > funky.Rproj
open funky.Rproj
</pre>
 
== Launch a project with a specified R version ==
https://support.rstudio.com/hc/en-us/articles/200486138-Changing-R-versions-for-RStudio-desktop
 
<ul>
<li>Linux. Consider to include the line in '''~/.profile''' file for a permanent solution or '''~/.bashrc''' for a project specific launch of rstudio.
<pre>
export RSTUDIO_WHICH_R=/opt/R/4.3.2/bin/R; rstudio ~/Project/Project.Rproj
</pre>
<li>Mac (one long line). Consider to include an alias in '''~/.zshrc''' file.
{{Pre}}
open -n -a RStudio ~/Project/Project.Rproj --env RSTUDIO_WHICH_R=/Library/Frameworks/R.framework/Version/4.3-arm64/Resources/R
</pre>
</ul>
 
== Closing a project vs 'X' ==
* Closing a project will not close RStudio. The current project becomes '(None)'.
* Pressing 'X' will close RStudio IDE.


== Sharing a Project with multiple users ==
== Sharing a Project with multiple users ==
Line 384: Line 618:
== Project settings ==
== Project settings ==
Menu -> Tools -> Project Options...  The changes are saved in XXX.Rproj file.
Menu -> Tools -> Project Options...  The changes are saved in XXX.Rproj file.
== How to remove a project name from the Rstudio Projects menu ==
* Edit the file [https://community.rstudio.com/t/how-to-remove-a-project-name-from-the-rstudio-projects-menu/6820/3 project_mru]
* I could not find the file on macOS. However, there is a solution. If I delete the .Rproj file for the project I don't want to keep and I try to open the project from RStudio's recent list (top-right corner), RStudio will give a message the project does not exist or remove. After I acknowledge it, the project name will be removed from the recent project list.


== .Rproj.user directory ==
== .Rproj.user directory ==
Line 442: Line 680:
* https://stackoverflow.com/questions/49549962/how-to-give-a-title-for-a-block-of-r-codes-denoted-by-five-or-more-e-x
* https://stackoverflow.com/questions/49549962/how-to-give-a-title-for-a-block-of-r-codes-denoted-by-five-or-more-e-x
* [https://support.rstudio.com/hc/en-us/articles/200484568-Code-Folding-and-Sections Code Folding and Sections] and [https://support.rstudio.com/hc/en-us/articles/200710523-Navigating-Code Navigating Code] from RStudio
* [https://support.rstudio.com/hc/en-us/articles/200484568-Code-Folding-and-Sections Code Folding and Sections] and [https://support.rstudio.com/hc/en-us/articles/200710523-Navigating-Code Navigating Code] from RStudio
* '''Code chunk navigator''' included at the bottom of the R Markdown window pane; see [https://www.dataquest.io/blog/r-markdown-tips-tricks-and-shortcuts/ R Markdown Tips, Tricks, and Shortcuts] 2020
* Hadley's [http://r-pkgs.had.co.nz/r.html#style Commenting guidelines]. Note that the [http://r-pkgs.had.co.nz/man.html object documentation] lines won't show up in the navigation section.
* Hadley's [http://r-pkgs.had.co.nz/r.html#style Commenting guidelines]. Note that the [http://r-pkgs.had.co.nz/man.html object documentation] lines won't show up in the navigation section.
* Function definitions do not form a code section though the functions are shown in the R script '''function menu''' (this term is borrowed from [https://support.rstudio.com/hc/en-us/articles/200710523-Navigating-Code Navigating Code]) post. Function definitions are nested under sections.
* Function definitions do not form a code section though the functions are shown in the R script '''function menu''' (this term is borrowed from [https://support.rstudio.com/hc/en-us/articles/200710523-Navigating-Code Navigating Code]) post. Function definitions are nested under sections.
* A [https://twitter.com/hi_im_alise/status/1539746290564997121?s=20&t=511ks15vTV3xf3wRfZDQ_Q screenshot] from twitter


The best practice to include a comment for a block of code is  
The best practice to include a comment for a block of code is  
Line 475: Line 715:
# Section 2 ###
# Section 2 ###
</pre>
</pre>
== Create a section within a chunk ==
It's useful to create a label to split a long chunk for easy navigation. Below is an example where we create two labels in a chunk.
<pre>
```{r}
# BRCA1 ----
...
# BRCA2 ----
...
```
</pre>
== shiny ui.R ==
For the ui part, it seems RStudio does not do code folding correctly. '''Sublime Text''' and '''VS Code''' do well in this case.


= Jobs =
= Jobs =
Line 481: Line 735:


= Python =
= Python =
[https://www.business-science.io/business/2018/10/08/python-and-r.html R and Python: How to Integrate the Best of Both into Your Data Science Workflow]
<ul>
<li>https://rstudio.github.io/reticulate/, [https://rstudio.github.io/reticulate/reference/install_miniconda.html install_miniconda()] </li>
<li>[https://www.rstudio.com/blog/three-ways-to-program-in-python-with-rstudio/ Three Ways to Program in Python With RStudio] </li>
<li>[https://www.youtube.com/watch?v=OtINRCXprGg How to set up Python in RStudio] (video)
<pre>
install.packages("reticulate")
library(reticulate)
install_miniconda()
# $ conda activate r-reticulate
# $ conda deactivate
</pre>
Create a virtual environment
<pre>
# virtualenv python
 
# source python/bin/activate
# source python/YourVirtualEnvironment
# which python
 
# pip install numpy pandas
</pre>
Configure reticulate in R console
<pre>
Sys.setenv(RETICULATE_PYTHON = "python/bin/python")
</pre>
Run your python code in RStudio
<pre>
py_run_string("python code here")
py_run_file("my_python_code.py")
</pre>
</li>
<li>[https://www.business-science.io/business/2018/10/08/python-and-r.html R and Python: How to Integrate the Best of Both into Your Data Science Workflow]
</li>
</ul>


= Addins =
= Addins =
Line 503: Line 790:


== styler ==
== styler ==
Non-invasive pretty printing of R code https://github.com/r-lib/styler  
Non-invasive pretty printing of R code https://github.com/r-lib/styler
 
{{Pre}}
R> styler:::style_active_file()
Using style transformers `styler::tidyverse_style()`
The R.cache package needs to create a directory that will hold cache files. It is convenient to use  ‘/Users/XXX/Library/Caches/R/R.cache’ because it follows the standard on your operating system and it remains also after restarting R. Do you wish to create the '/Users/XXX/Library/Caches/R/R.cache' directory? If not, a temporary directory (/var/folders/2q/slryb0rx4tj97t66v7l6pwvr_z6g3s/T//RtmplfQTrd/.Rcache) that is specific to this R session will be used. [Y/n]:
</pre>


== [https://github.com/ThinkR-open/remedy remedy]: rmarkdown helper ==
== [https://github.com/ThinkR-open/remedy remedy]: rmarkdown helper ==
Line 520: Line 813:
== beautifyR ==
== beautifyR ==
https://github.com/mwip/beautifyR#beautifyr-in-action RStudio addin for formatting Rmarkdown tables and R multi-line comments
https://github.com/mwip/beautifyR#beautifyr-in-action RStudio addin for formatting Rmarkdown tables and R multi-line comments
= Print an R code with line numbers =
Use '''cat -n''' and the [https://pandoc.org/faqs.html margin option] in pandoc.
<pre>
cat -n mycode.R | pandoc -V geometry:margin=1cm -o mycode.pdf
cat -n mycode.R | pandoc -V geometry:"top=1cm, bottom=1.5cm, left=2cm, right=1cm" -o mycode.pdf
</pre>
= prettycode: Pretty Print R Code in the Terminal =
[https://rdrr.io/cran/prettycode/man/prettycode.html prettycode: Pretty Print R Code in the Terminal]


= Diagnosis =
= Diagnosis =
rstudio &rarr; run-diagnostics
rstudio &rarr; run-diagnostics


= RStudio Package Manager =
== there is no package called 'rmarkdown' ==
* https://docs.rstudio.com/rspm/admin/index.html
https://github.com/rstudio/rstudio/issues/4092
* [https://resources.rstudio.com/webinars/introduction-to-the-rstudio-package-manager-sean-lopp Introduction to the RStudio Package Manager] - Sean Lopp
 
* [https://support.rstudio.com/hc/en-us/articles/360009982613-How-do-I-update-packages-in-RStudio-Package-Manager- How do I update packages in RStudio Package Manager?]
= RStudio Voices =
[https://blog.rstudio.com/2021/08/12/rstudio-voices-julia-silge/ RStudio Voices - Julia Silge]
 
= Contests =
== Tables ==
[https://blog.rstudio.com/2021/09/30/rstudio-table-contest-2021/ An RStudio Table Contest for 2021]
 
== Shiny ==
[https://blog.rstudio.com/2021/06/24/winners-of-the-3rd-annual-shiny-contest/ Winners of the 3rd annual Shiny Contest]


= Conferences =
= Conferences =
Line 535: Line 846:
** [https://www.mango-solutions.com/blog/rstudioconf-2019 2019 roundup]
** [https://www.mango-solutions.com/blog/rstudioconf-2019 2019 roundup]
* https://resources.rstudio.com/rstudio-conf-2020
* https://resources.rstudio.com/rstudio-conf-2020
* [https://blog.rstudio.com/2021/02/01/enjoy-more-rstudio-global-2021/ Enjoy More Rstudio::global(2021)]
* [https://www.rstudio.com/blog/talks-and-workshops-from-rstudio-conf-2022/ Talk recordings and workshop materials from rstudio::conf(2022)], [https://bioc2022.bioconductor.org/schedule/ Schedule],[https://adisarid.github.io/post/what-i-learned-from-rstudio-conf-2022/ Some takeaways from rstudio::conf 2022], [https://www.rstudio.com/blog/four-announcements-from-rstudio-conf-2022/ Four announcements from rstudio::conf(2022)]
* 2023 [https://github.com/posit-conf-2023 Workshop materials], [https://www.youtube.com/playlist?list=PL9HYL-VRX0oRFZslRGHwHuwea7SvAATHp Youtube].
= Alternatives =
== Positron ==
* https://github.com/posit-dev/positron
* [https://www.appsilon.com/post/introducing-positron Introducing Positron: A New, Yet Familiar IDE For R And Python]
* '''Workspace'''
** The workspace file has an extension *.code-workspace
** Use File -> Open workspace from file ...
** Use File -> Save workspace as ...
* Single or double click a file
** [https://stackoverflow.com/a/38723094 How can I prevent VS Code from replacing a newly opened, unmodified (preview) tab with a subsequently opened one?]
** Positron -> Settings -> Settings and search by 'workbench.editor.enablePreview'
* Setup tips
** [https://www.youtube.com/watch?v=VPHuCl8asjQ Positron IDE for R & Python | How to Install & Use | Better than RStudio?] Aug 9, 2024
== RKWard ==
https://rkward.kde.org/

Revision as of 21:10, 31 August 2024

Different tastes

Server

Docker

  • This is useful if RStudio desktop is not available for your Linux distribution. Another choice is Singularity if we don't have sudo privilege.
  • Running RStudio Inside a Container

Cloud

https://rstudio.cloud/. You can sign up using gmail or github account.

Free account limitation: RStudio Cloud cannot read in 1GB file? It seems 1GB memory limit still holds as of today (2020-03-09). Use cat /sys/fs/cgroup/memory/memory.limit_in_bytes to find out the limit (1073741824 in this case).

Upload a file: Click 'Files' under the bottom right pane (Files-Plots-Packages-Help-Viewer). There is an "upload" button next to the "New folder" button over there.

I can install a package from a source with URL. So I don't need to upload the packages to RStudio.

If it took too long to load an existing project (such as shiny projects), I just need to relaunch the project (Click three dots icon and select the 3rd option).

I got an error "Unexpected response from server" when I try to upload a file around 300MB. 2020-02-26.

I got an error "Error occurred during transmission" when I try to run an R statement.

What's New on RStudio Cloud - September 2021

Desktop

Build from source See https://github.com/rstudio/rstudio/blob/master/INSTALL https://github.com/rstudio/rstudio/blob/main/INSTALL for installation instruction.

sudo apt-get install git cmake build-essential libboost-all-dev libssl-dev libbz2-dev libpam-dev libxslt1-dev libsqlite3-dev libpq-dev libmysqlclient-dev pandoc libcurl4-openssl-dev libxml2-dev libxslt1-dev zlib1g-dev libreadline-dev libpcre3-dev liblzma-dev libblas-dev libatlas-base-dev liblapack-dev libapparmor-dev libedit2 libobjc4 openjdk-11-jdk

git clone https://github.com/rstudio/rstudio.git

cd rstudio
mkdir build
cd build
cmake .. -DRSTUDIO_TARGET=Desktop -DCMAKE_BUILD_TYPE=Release
sudo make install

(2023) Electron Desktop. The Electron desktop (under development) replaces QtWebEngine with Electron. The sources live in src/node/desktop; it is written primarily in TypeScript.

To build Rstudio from source in Ubuntu (outdated):

  • Install R.
  • Install Qt 4.
  • Download a release version tarball of source code. Do not grab from github master branch. Sometimes the preview version works but the release version cannot be compiled. For example, the release version 0.98.507 would give a build error from /opt/QRstudio-QtSDK/Desktop/4.8.0/gcc/include/QtCore/gstring.h, but the preview version 0.98.836 (May 11th, 2014) works fine.
  • Make sure git is installed/available.
  • Install dependencies (note that installing boost will take a few minutes. Make sure there are 2GB memory or will get a memory related error when running make install)
cd rstudio-rstudio-dbf531d  # the number at the end depending on the source
cd dependencies/linux
./install-dependencies-debian
  • Create build directory
mkdir build
cd build
  • Configure by running cmake
cmake .. -DRSTUDIO_TARGET=Desktop -DCMAKE_BUILD_TYPE=Release

If something is wrong related to boost library, go back to step 1. Then type (installing boost library takes a while)

cd dependencies/linux 
run ./install-boost

And for some reason, when I try to run cmake (OS is 32-bit LXLE running on VM), I get the following error

CMake Error at /usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:108 (message):
  Could NOT find Qt4 (missing: QT_QTWEBKIT_INCLUDE_DIR QT_QTWEBKIT_LIBRARY
  QT_QTDBUS_INCLUDE DIR QT_QTDBUS_LIBRARY) (found suitable version "4.8.6", minimum required
  is "4.8.0")
  • Build and Install
sudo make install

For RStudio Desktop on Linux, make install automatically creates an entry in the Applications -> Programming menu for RStudio. The rstudio can be launched by /usr/local/lib/rstudio/bin/rstudio.

Releases

Discussion

Preferences

rstudio.prefs

rstudio.prefs package, on CRAN

Configuration file

~/.config/rstudio/rstudio-prefs.json (checked in Linux & macOS).

Note: the file exists under each project folder. However if I modify the file by adding an editor theme like "editor_theme": "Xcode" for project-specific, it won't be taken.

Where else RStudio searches for rstudio-prefs.json? Currently, only a small handful of RStudio preferences can be set on a project (not global) level.

RStudio Theme

Background color (v1.1.383, see an animation on this post)

There are 3 choices of RStudio theme (Using RStudio Themes):

  • Classic + selected Editor theme: Code and Console/Terminal are dark, Environment/history/connections and Files/Plots/Packages/Help/Viewer are white (good when doing finding). But the 'R Markdown' tab does not show a working rotation symbol.
  • Modern: 4 panels are all dark (my choice).
  • Sky: 4 panels are all dark

One good-looking option is also change the layout like this one. So source code take half and console and plot each takes a quarter of the screen.

Background color of plot pane becomes black. It turns out the reason is the user is using a transparent background in his plotting routine.

Custom Theme support was added in RStudio v1.2.

Editor theme

  • Using Themes in the RStudio IDE
  • Themes from RStudio User Guide
    • .ace_selection
  • Vibrant Ink,
    • Vibrant ink rstheme.png
    • Advantages: 1) dark background and 2) (more important) they draw rectangles using bright colors around the words we search.
    • VS code has a better highlight of search words. In RStudio, it only add a rectangle on the edge but VS code will change the background color of search word.
    • https://github.com/captaincaed/rstudio/blob/main/vibrant_ink_SB_2.rstheme. Download the file and open it in RStudio. Change the syntax highlight from Text file to CSS.
    • My modification: change the border of rectangles from blue to orange for all matched find words (line 39). After using rstudioapi::addTheme(), the theme file appears in ~/.configrstudio/themes directory. We may open the file in RStudio and experiment the setting. After that, we can call rstudioapi::applyTheme("Vibrant Ink SB 2") to apply the change. Note the theme name is at the first line of the file.
.ace_marker-layer .ace_selected-word {
  border: 1px solid #FF6600
}

Change selected word highlight color in source - theme

R markdown, inline output for plots

tab and spaces

Options -> Code -> Editing. Tab width is 2 by default.

Wish there is an option for this depending on the language. For example some C code uses 4 spaces as tab.

Mouse Cursor

Toolbar

View -> Hide Toolbar

RStudio Package Manager

Change repository

R mirrors

  • chooseCRANmirror(): this actually changes the CRAN mirror. It is done mainly interactively.
  • Non-interactive method.
    local({
      r <- getOption("repos")
      r["CRAN"] <- "https://mirror.las.iastate.edu/CRAN"
      options(repos = r)
    })
  • setRepositories(ind=1:2) (both non-interactive or interactive): this allows to install packages from Bioconductor. After the change, we can use RStudio or the command install.packages() to install R package from Bioconductor. See setRepositories documentation.
1: + CRAN
2: + BioC software
3:   BioC annotation
4:   BioC experiment
5:   CRAN (extras)
6:   Omegahat
7:   R-Forge
8:   rforge.net

In my case, stringr package source code in cloud.r-project.org (default in RStudio or 0-Cloud from chooseCRANmirror()) is 1 week old. That version of source code is now archived and the URL shown from the output of install.packages() cannot be found. When I switch to USA-IA mirror, it has the latest version.

Use options("repos") to see its effect.

options("repos")
$`repos`
                                        CRAN                                     BioCsoft 
       "https://mirror.las.iastate.edu/CRAN" "https://bioconductor.org/packages/3.7/bioc"

Change R version

Install R from Source from Posit Documentation.

Desktop

https://support.rstudio.com/hc/en-us/articles/200486138-Changing-R-versions-for-RStudio-desktop

On Linux, the default R can be found by which R in the command line. If you want to override which version of R is used then you can set the RSTUDIO_WHICH_R environment variable to the R executable that you want to run against. For example:

export RSTUDIO_WHICH_R=/opt/R/3.5.0/bin/R

Not that in order for RStudio to see this environment variable when launched from the Ubuntu desktop Applications menu (as opposed to from a terminal) it must be defined in the ~/.profile file.

Server

Using multiple versions of R with RStudio Server Pro

pandoc

$ pandoc --version
pandoc 2.7.3

$ /Applications/RStudio.app/Contents/MacOS/pandoc/pandoc -v
pandoc 2.3.1

To use the system's pandoc, create/modify project's .Renviron file and include a line to something like

PATH="/usr/local/bin/:${PATH}"

Get help on firefox/chrome browser

(The help panel is kind of small). If we want to do a search, we can only do that with the small window. We can't do a search if we open the help in a new window.

No, it can't. But alternatively, if we click "Show in a new window" icon, it will bring the help on an independent window.

> getOption("browser")
function (url) 
{
    .Call("rs_browseURL", url)
}
<environment: 0x1121bda60>

Tips

Freeze

Find in files

There is no need to use the "grep" command in a Terminal anymore.

  • Method 1: Ctrl + . (aka. Go to File/Function). This will quickly list all files in the project containing the keyword.
  • Method 2: Edit -> Find in Files. It will open a tab called "Find in Files" after the tabs "Console, Terminal" and before the tab "Background jobs". This will list all files with lines of code containing the keyword in the specified folder.

Command palette

Access it with Ctrl + Shift + P (Windows / Linux) or Cmd + Shift + P (macOS)!

object 'partition_yaml_front_matter' not found

Error on opening RStudio. The solution of disabling Prompt to install missing R packages discovered in R source files in the Settings works for me.

Outline

Click a small icon/button at the top-right corner of the code panel.

  • For an Rmd file, it gives an online (all section headers) of the file.
  • For an R file, it list all functions in the document.

Some good examples from rstudio.

Install package

(Mac OS). If I install a package in R console, the package will be installed under '/Users/XXX/Library/R/3.6/library'.

But if I install the package using RStudio's packages panel or through 'menu > Tools > Install Packages...', the package will go to "/Library/Frameworks/R.framework/Versions/3.6/Resources/library". So if we use remove.packages() without specify the lib parameter, it may there is no package that can be uninstalled. We can change the installation directory if we install the package using 'menu > Tools > Install Packages...' method. Here has some screenshots on Windows OS.

Visual Markdown Editor

RStudioVisualMode.png
  • Note when we switch from source mode to visual mode, RStudio will give us some warning. If we continue, it will modify the source code. Note: even we switch back to the Source mode, it won't undo the code change. If we want to undo the code change, we should do it by ourselves (ctrl+z/Cmd+z).
    • YAML will add markdown wrap: 72
    • Rmd document will wrap long lines. Itemized lines will be reformatted.
    • The response speed in Visual mode is slow. Arrow keys navigation seems not responding.
    • Inline images size is increased.
    • Outline button/option will be turned on.
  • Switch markdown editing mode between Source and Visual

Drag and drop formulas from Wikipedia into your R Markdown document

R Markdown Lesser-Known Tips & Tricks #1: Working in the RStudio IDE

Pop out the source pane to have its own window

Drag the tab outside the RStudio window to where you want your new code window to appear, or Click the "Show in new window" button on the editor toolbar (it's next to forward/back)

However, it seems we cannot move the popped out pane back to RStudio. If we just want to maximize one pane, we can use the keyboard shortcut "Ctrl+Shift+1" (source pane) or "Ctrl+Shift+2" (console pane); see Zoom in one pane.

Column selection

Click Alt.

options(width)

Once we resize the width manually with the mouse, the width will be changed at the same time.

Menu -> Code

  • For R code files *.R, it has "Insert Section" (a recommended way to insert a new section)
  • For R markdown files *.Rmd, it has "Insert Chunk" (just a short cut)

Restart R

Three ways

  • Session -> Restart R
  • .rs.restart()
  • command/ctrl + shift + F10

Note Restarting R in RStudio won't delete/clear workspace/objects but it unloads R packages.

We can use Session -> Clear Workspace or the command rm(list=ls()) to delete all objects.

debug location is approximate because the source is not available

install.packages("survminer", INSTALL_opts = "--with-keep.source --no-byte-compile")
debug(survminer::ggsurvplot)
ggsurvplot(...)

Using the RStudio Terminal

https://support.rstudio.com/hc/en-us/articles/115010737148-Using-the-RStudio-Terminal

On my Mac, I need to run chsh -s /bin/bash AND then source ~/.bashrc in order to enable the changes I want.

Why doesn't .bashrc run automatically?

Console scroll back

https://stackoverflow.com/a/59327459 It is still a problem as of 2021-02-22.

Snippet

Crash and log file

On my Mac, the crash report is saved at ~/Library/Logs/DiagnosticReports/rsession_XXXX.crash and the log file is saved at ~/.local/share/rstudio/log/ (From within RStudio: Help Menu -> Diagnostics -> Show Log Files).

See also RStudio Crash Report, RStudio Application Logs.

RStudioAbort.png

Open an SVG file from RStudio

It only display the file as a text file. It cannot let OS open the file:(

Check if R is running in RStudio

Sys.getenv("RSTUDIO") == "1"
# Or
.Platform$GUI == "RStudio"

Copilot

GitHub Copilot in Rstudio, it's finally here!

Install on Crouton

Test on my Asus (intel CPU) Chromebox/Crouton with Ubuntu 14.04.

(trusty)brb@localhost:~$ sudo dpkg -i '/tmp/mozilla_brb0/rstudio-1.0.44-amd64.deb' 
Selecting previously unselected package rstudio.
(Reading database ... 133157 files and directories currently installed.)
Preparing to unpack .../rstudio-1.0.44-amd64.deb ...
Unpacking rstudio (1.0.44) ...
dpkg: dependency problems prevent configuration of rstudio:
 rstudio depends on libjpeg62; however:
  Package libjpeg62 is not installed.

dpkg: error processing package rstudio (--install):
 dependency problems - leaving unconfigured
Processing triggers for shared-mime-info (1.2-0ubuntu3) ...
Processing triggers for hicolor-icon-theme (0.13-1) ...
Processing triggers for gnome-menus (3.10.1-0ubuntu2) ...
Processing triggers for desktop-file-utils (0.22-1ubuntu1) ...
Processing triggers for bamfdaemon (0.5.1+14.04.20140409-0ubuntu1) ...
Rebuilding /usr/share/applications/bamf-2.index...
Processing triggers for mime-support (3.54ubuntu1.1) ...
Errors were encountered while processing:
 rstudio

After I run sudo apt-get install libjpeg62, RStudio can be installed successfully.

Stop a command

  • Use the stop sign
  • Use "Interrupt R" under Session menu.

See Kill a process in R with RStudio

Mouse

Scroll different tabs using the mouse wheel after you click any one of tabs.

Keyboard shortcut

  • https://support.rstudio.com/hc/en-us/articles/200711853-Keyboard-Shortcuts (Help -> Keyboard Shortcut Quick Reference)
  • Customize the shortcuts.
  • https://www.dropbox.com/s/0moch6xocili6v9/RStudio%20Shortcuts.pdf?dl=0
  • Send shell script (*.sh) code line by line will be done in Terminal tab. If we click 'Run Script', it will call system() in R.
  • Knit an rmarkdown file
    • Mac: Shift + Cmd + k
    • Linux: Shift + Ctrl + k
  • (Aug 16, 2018) for some reason, run current line (CMD+Enter) will send random lines. It does not help if I assign a different key-bind. Update RStudio does not help either.
    • One way it still works is by selecting line(s) first and hitting the key-bind.
    • Another way is to go to Tools > Global options > Code. Change to Current line from the dropdown list next to CMD + Enter executes. The default is "Multiple-line R statements" which should be better since an R statement can spread several lines. The 3rd option "Multiple consecutive R lines" will send a block of R lines automatically which does not look ideal in most cases.

Line feed

Shift + Enter still works in RStudio. Shift+Enter Is a Secret Shortcut Everyone Should Know.

Move focus to source/console

  • Ctrl + 1: source
  • Ctrl + 2: console

These are the default.

Zoom in/out on one pane/window

  • Ctrl + Shift + 1: source
  • Ctrl + Shift + 2: console
  • Ctrl + Shift + 3: file viewer
  • Ctrl + Shift + 4: environment
  • Ctrl + Shift + 0: show all panes

Jump to the matching brackets

Ctrl + p

Show previous/next Plot

By default, they are "Ctrl + Alt + F11" and "Ctrl + Alt + F12". But they have a conflict with other shortcuts in RStudio IDE itself or with the (Linux/Mint) system. In my case, Ctrl+Alt+F11 will escape from Linux Desktop:( Also the Quick Reference shows these bindings had a conflict: Ctrl + Alt + F11 represents Previous Terminal or Previous Plot.

I change the shortcuts to Alt+Left and Alt+Right (directly use keyboard to change it). It works but there is a delay if the plot is more complicated (6 seconds on a 10000 genes heatmap). These new assignment works on Mac and Linux.

Navigate previous commands

  • Cmd + up/down arrow keys (Mac)
  • Ctrl + up/down arrow keys (Linux)

Viewer pane

View() output

Save View() output of RStudio as html

Load all when developing a new package

The ctrl-shift-L shortcut which not only unloads/loads the package, but exports all unexported objects, including all pkg data and internal functions. Super handy debugging!

Automatically reformat code

  • CMD + Shift + A (mac)
  • Ctrl + Shift + A (Windows)

Fix code spacing, reindent lines

CMD + i

History panel

If we want to rerun lines from the history panel, just highlight the lines and then either click the "To Console" button or press the "Enter" key.

See Using Command History from RStudio.

RStudio server

rsession.conf

KVM

Multiple Rstudio Server instances using a single R/LaTeX install with KVM

RStudio Server Installation on Ubuntu

RStudio Server on Amazon EC2

2FA

Using OTP (one-time passwords) in rstudio server open source

Raspberry Pi

RStudio and Git

Plots window

Where does RStudio save your plots history

Save all plots already present in the panel of Rstudio. In RStudio, every session has a temporary directory that can be obtained using tempdir(). Inside that temporary directory, there is another directory that always starts with "rs-graphics" and contains all the plots saved as ".png" files.

Interactive plots: manipulate

Interactive Plotting with Manipulate in the RStudio IDE.

Sometimes it does not work:(

Plot from Rmd file does not show up in RStudio's plot window

options(device = "RStudioGD") # or dev.off()
dev.new()
...

Plot in Rstudio not showing up

> dev.cur()
RStudioGD 
        2

Note: when I run a ggsurvplot() statement from an Rmd file, the plot is shown in the source panel instead of the plot window. I could not find the plot at first since the chunk is long. dev.cur() returns null device instead of RStudioGD after I call ggsurvplot(). It could be an issue with ggsurvplot() since a simple ggplot() call is fine. In this case, I can save ggsurvplot() to an object and print the object will show the plot in the plot window.

Overlap problem

https://stackoverflow.com/questions/45395220/legends-overlapping-the-plots-in-rstudio

Project

Using Projects

  • RStudio Projects and Working Directories: A Beginner’s Guide. Replacing setwd() by making file paths relative.
    • The RStudio project file is a file that sits in the root directory, with the extension .Rproj.
    • Everything relating to that analysis or project should only happen within that directory.
    • When opening an existing project, you should open the .Rproj file first and only subsequently open any R scripts (extensions with .R) from the RStudio session, rather than going straight to the R scripts to open them.
    • Structuring your working directory: Data, Script, Output.
  • The folder name will be used to represent a project on the top-right corner of RStudio.
  • Working with Multiple Projects at Once

Create an .Rproj file

mkdir funky
cd funky
echo "Version: 1.0" > funky.Rproj
open funky.Rproj

Launch a project with a specified R version

https://support.rstudio.com/hc/en-us/articles/200486138-Changing-R-versions-for-RStudio-desktop

  • Linux. Consider to include the line in ~/.profile file for a permanent solution or ~/.bashrc for a project specific launch of rstudio.
    export RSTUDIO_WHICH_R=/opt/R/4.3.2/bin/R; rstudio ~/Project/Project.Rproj
    
  • Mac (one long line). Consider to include an alias in ~/.zshrc file.
    open -n -a RStudio ~/Project/Project.Rproj --env RSTUDIO_WHICH_R=/Library/Frameworks/R.framework/Version/4.3-arm64/Resources/R
    

Closing a project vs 'X'

  • Closing a project will not close RStudio. The current project becomes '(None)'.
  • Pressing 'X' will close RStudio IDE.

Sharing a Project with multiple users

https://support.rstudio.com/hc/en-us/articles/201751487-Sharing-a-project-with-multiple-users

Project settings

Menu -> Tools -> Project Options... The changes are saved in XXX.Rproj file.

How to remove a project name from the Rstudio Projects menu

  • Edit the file project_mru
  • I could not find the file on macOS. However, there is a solution. If I delete the .Rproj file for the project I don't want to keep and I try to open the project from RStudio's recent list (top-right corner), RStudio will give a message the project does not exist or remove. After I acknowledge it, the project name will be removed from the recent project list.

.Rproj.user directory

Using Projects

We probably don't want to share this directory with others.

This directory is also automatically added to .Rbuildignore, .gitignore, etc. if we check the option Create a git repository when creating a new project.

Note when we create a new project, we can check the option Open in a new session (default is not checked).

RstudioNewproj.png

Script for creating a new project in Rstudio

https://stackoverflow.com/a/26127716. Below is a modified with my fix. It will generate a new file XXX.Rproj under the current working directory.

myProject <- function(proj, ...) {

    #require(ProjectTemplate)
    #create.project(proj, ...)

    x <- c("Version: 1.0", "", "RestoreWorkspace: Default", "SaveWorkspace: Default", 
        "AlwaysSaveHistory: Default", "", "EnableCodeIndexing: Yes", 
        "UseSpacesForTab: Yes", "NumSpacesForTab: 4", "Encoding: UTF-8", 
        "", "RnwWeave: knitr", "LaTeX: pdfLaTeX")

    #cat(paste(x, collapse="\n"), file=file.path(proj, paste0(basename(proj), ".Rproj")))
    cat(paste(x, collapse="\n"), file=paste0(basename(proj), ".Rproj"))
    message(paste0(basename(proj), ".Rproj has been created"))
}

myProject("MyNewProject") # It will generate the file <MyNewProject.Rproj>.

Running A Data Project In R

https://kkulma.github.io/2018-03-18-Prime-Hints-for-Running-a-data-project-in-R/

  • Use R projects. Always
  • Describe the purpose of your code / project.
  • Load all necessary packages in the beginning of your script & consider calling functions in a package via ::
  • Name your code sections and use them for quick navigation
  • Make your life easier and mark your code when you need to
  • Write your code as if someone was going to use it without communicating with you. From. Day. One
  • Name your files like a Pro: Machine readable, human readable & play well with ordering
    • Put something numeric in your file name first.
    • use the YYYY-MM-DD format for dates
    • regular expression and globbing friendly
    • easy to compute on using delimiters
    • left pad other numbers with zeroes
  • With big, complex data projects use project pipeline
    • load.R
    • clean.R
    • func.R
    • do.R
  • Never save your workspace
  • Before publishing/sharing your code, run it in the fresh workspace

Comment, navigation and code folding

The best practice to include a comment for a block of code is

  • Code > Insert Section (this will create something like # Section One --------------------------------- )
  • At least one number sign (pound sign) before the title PLUS at least 4 of number signs/dash signs/equal signs at the end

Good examples

#### My section ####

# My section ####

# My section ----

Bad example 1 (this will show 2 lines of (Untitled) in RStudio nagivation)

################
# Section 1
################

Bad example 2 (this will not show anything in the navigation)

# Section 2

# Section 2 #

# Section 2 ##

# Section 2 ###

Create a section within a chunk

It's useful to create a label to split a long chunk for easy navigation. Below is an example where we create two labels in a chunk.

```{r}
# BRCA1 ----
...
# BRCA2 ----
...
```

shiny ui.R

For the ui part, it seems RStudio does not do code folding correctly. Sublime Text and VS Code do well in this case.

Jobs

Python

Addins

Step-by-step to create an addin R package

Defining Your Own Shortcut in RStudio

  1. Create an R package project in RStudio
  2. In R console to create a new file: usethis::use_r("set_new_chapter")
  3. Type and finish the new R function set_new_chapter()
  4. Create a new folder inst/rstudio. Create a new text file "addins.dcf"
  5. In R console, type a few R commands to finalize the package and output a package tarball

To use the package in RStudio

  1. Install the new package as usual
  2. In RStudio, go to Tools > Modify Keyboard Shortcuts… and search for "dashes". Clicking inside the empty "Shortcut" field and pressing the desired key-combination (eg CMD + d) on your keyboard. Click "Apply". Done
  3. Go to R editor and type some comments. Now pressing the keyboard shortcut (CMD + d) and dashes will be inserted from the cursor location.

styler

Non-invasive pretty printing of R code https://github.com/r-lib/styler

R> styler:::style_active_file()
Using style transformers `styler::tidyverse_style()`
The R.cache package needs to create a directory that will hold cache files. It is convenient to use  ‘/Users/XXX/Library/Caches/R/R.cache’ because it follows the standard on your operating system and it remains also after restarting R. Do you wish to create the '/Users/XXX/Library/Caches/R/R.cache' directory? If not, a temporary directory (/var/folders/2q/slryb0rx4tj97t66v7l6pwvr_z6g3s/T//RtmplfQTrd/.Rcache) that is specific to this R session will be used. [Y/n]: 

remedy: rmarkdown helper

facilitate writing in markdown with RStudio

RegExplain

https://github.com/gadenbuie/regexplain

esquisse

GGplot2 > esquisse

compareWith (meld)

beautifyR

https://github.com/mwip/beautifyR#beautifyr-in-action RStudio addin for formatting Rmarkdown tables and R multi-line comments

Print an R code with line numbers

Use cat -n and the margin option in pandoc.

cat -n mycode.R | pandoc -V geometry:margin=1cm -o mycode.pdf
cat -n mycode.R | pandoc -V geometry:"top=1cm, bottom=1.5cm, left=2cm, right=1cm" -o mycode.pdf

prettycode: Pretty Print R Code in the Terminal

prettycode: Pretty Print R Code in the Terminal

Diagnosis

rstudio → run-diagnostics

there is no package called 'rmarkdown'

https://github.com/rstudio/rstudio/issues/4092

RStudio Voices

RStudio Voices - Julia Silge

Contests

Tables

An RStudio Table Contest for 2021

Shiny

Winners of the 3rd annual Shiny Contest

Conferences

Alternatives

Positron

RKWard

https://rkward.kde.org/