First commands

You can type R commands directly into the ‘console’ (see here) and see the result there, but you should make a habit of working in an RMarkdown file. This keeps a record of everything you try, and makes it easy to edit/amend things which didn’t quite work.

Create a new Rmarkdown document from the ‘file’ menu in RStudio.

To run code in the RStudio interface put your cursor on a line within an R Block (or select the code you want to run), and press Ctrl-Enter. The result will appear below the code block.

The command in the R block below prints (i.e. shows on screen) the first few rows of a dataset that is built-in to R as an example, called mtcars.

Place your cursor somewhere in the line the command is on and run it by typing Ctrl-Enter, shown in this brief video:

Create an R block in RMarkdown, then run some simple commands.

head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

If you are reading this from within RStudio, running head(mtcars) makes an interactive table in your document, which you can use this to browse the mtcars dataset.

If you are still reading the compiled html or pdf document you will see a static table containing the same data.

Hopefully at this point it’s obvious that RStudio and RMarkdown give you:

  • A nice place to work your data interactively
  • A way to ‘show your workings’ and save this for later
  • A way to share your analysis