Below are miscellaneous tricks for coding in R and for using the R Studio interface. Also, to get started, here’s a helpful link about basics in authoring R Markdown code: https://rmarkdown.rstudio.com/authoring_basics.html
Code Formatting
Folding the code blocks. This is really useful if you’re working with a long file with many lines of code. When you first open a file you previously wrote, it’ll have all of the code blocks unfolded. If you just want to go back to one section and e.g., change a figure line color, it’s way easier to see the relevant code section with folded blocks. Either via the Edit menu or keyboard shortcut you can quickly fold all of the code blocks and then only unfold the ones you need to work with.
Keyboard: Mac: COMMAND + OPTION + O Windows: ALT + O
Menus: Edit -> Folding -> Collapse All
Viewing the outline. This is also useful if you’re working with a lot of code. You can pull up a sidebar with an outline of your code.
Keyboard: Mac: COMMAND + SHIFT + O Windows: CTRL + SHIFT + O
Printing Useful Information
Print the R version you’re using.
R.version
Print the citation for a package.
citation(package="psych")
Plotting
Pull the x and y axis limits from a ggplot.
ggplot_build(g1)$layout$panel_scales_x[[1]]$range$range
ggplot_build(g1)$layout$panel_scales_y[[1]]$range$range
Coding
R recognizes partial variable names if unique. This is less of a tip (because it’s bad practice) and more of something to note. If you have a long-ish variable name that’s unique, R will let you call that variable with only the first part of its unique name. For instance:
I’m not sure I’d really recommend doing this… because you obviously want to be super sure you’re calling the intended variable for whatever function you’re running. However, it’s something to note that R does — because, for instance, it was driving me crazy until I realized this was the case; I thought that R was loading the wrong dataset with differently named variables, or that something else funky was going on!