Raul Guarini Riva
Raul Guarini Riva

Reputation: 795

How to run code section by section in RStudio?

I'm new to RStudio (and to R as a whole to be fair) and I was wondering if there is a command or shortcut that would let me run the code in the console section by section.

I'm using 4 " - " to separate different chunks of my code. For example:

# ---- Item 3 ----
ols_reg <- lm(diff_mkt_share ~ ceu + canais + preco, 
           data = vec_data)
summary(reg1)

# ---- Item 6 ----
install.packages("AER")     # Pacote standard pra Ecoometria Aplicada em R

library("AER")
inst <- c(dados$z1, dados$z2)
cbind(vec_data, inst)

iv_reg <- ivreg(diff_mkt_share ~ ceu + canais + preco | ceu + canais + inst,
              data = vec_data)
summary(reg2)

Rstudio will let me easily hide Item 3 or Item 6 sections but is there a way (as there is one in MATLAB) such that I can run a full chunk of code with only a keystroke? Sure, I could press Cmd + Enter several times but it wouldn't be efficient for large chunks.

Upvotes: 8

Views: 19243

Answers (5)

gaspar
gaspar

Reputation: 1078

  • Windows: Ctrl+Alt+T
  • Mac: Cmd+Option+T

See: https://support.rstudio.com/hc/en-us/articles/200711853-Keyboard-Shortcuts "Run the current code section"

And for defining code sections, see: https://support.rstudio.com/hc/en-us/articles/200484568-Code-Folding-and-Sections-in-the-RStudio-IDE/#code-sections

Upvotes: 5

EKnos
EKnos

Reputation: 35

Simply enclose it in brackets: { all contiguous lines of code }

Upvotes: -3

Sumax
Sumax

Reputation: 719

I utilize the shortcut: CTRL+ALT+C or CMD+Option+C key to run the current code chunk in RMarkdown, w/o selecting any lines to run. For more shortcut methods: check out the R Studio Cheatsheet.

Upvotes: 0

lukeA
lukeA

Reputation: 54277

In the RStudio source pane, you can run the current section ("chunk") of an R script by hitting Shift+Alt+T. No need for Notebooks.

Upvotes: 1

BLT
BLT

Reputation: 2552

Check out R Notebooks in recent versions of RStudio. Then you can put your code in different chunks and run them as you please.

An R Notebook is an R Markdown document with chunks that can be executed independently and interactively, with output visible immediately beneath the input.

If you must use an R script, I usually just highlight the multiple lines of code I want to run at once and do a Cmd + Enter or Ctrl + r, depending on what OS I'm using.

Upvotes: 6

Related Questions