Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run code section by section in RStudio?

Tags:

r

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.

like image 593
Raul Guarini Riva Avatar asked Sep 07 '17 15:09

Raul Guarini Riva


People also ask

How do I run a section of code in RStudio?

To execute the line of source code where the cursor currently resides you press the Ctrl+Enter key (or use the Run toolbar button): After executing the line of code, RStudio automatically advances the cursor to the next line. This enables you to single-step through a sequence of lines.

How do I run a selection in R?

Shortcuts to run R codeCtrl + Enter – Runs the current line and jumps to the next one, or runs the selected part without jumping further. Alt + Enter – Allows running code without moving the cursor to the next line if you want to run one line of code multiple times without selecting it.

How do I run all codes in R?

In addition, in Rstudio you can run the entire script by pressing Ctrl + Shift + Enter without selecting any code. In addition, there is a shortcut to source the current script file ( Ctrl + Shift + s ), which runs the script without echoing each line.

Which two parts of RStudio can you execute code select all that apply?

Select all that apply. In RStudio, you can execute code in the R console pane and the source editor pane.


1 Answers

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.

like image 170
BLT Avatar answered Oct 05 '22 22:10

BLT