Using R as a Calculator
Introduction to R
Much of your time in R will be spent in the R interactive
console. This is where you will run all of your code, and can be a
useful environment to try out ideas before adding them to an R script
file. This console in RStudio is the same as the one you would get if
you typed in R
in your command-line environment.
The first thing you will see in the R interactive session is a bunch of information, followed by a ">" and a blinking cursor. In many ways, this is similar to the shell environment you learned about during the shell lessons: it operates on the same idea of a "Read, evaluate, print loop": you type in commands, R tries to execute them, and then returns a result.
Using R as a calculator
The simplest thing you could do with R is to do arithmetic:
1 + 100
Output |
---|
|
And R will print out the answer with a preceding "[1]". Don't worry about this for now; we'll explain that later. For now, think of it as indicating output.
If you type in an incomplete command, R will wait for you to
complete it. If you are familiar with Unix Shell's bash, you may recognize this
behavior from bash.
> 1 +
Output |
---|
|
Any time you hit return, and the R session shows a "+" instead of a ">", it means it's waiting for you to complete the command. If you want to cancel a command, you can hit Esc, and RStudio will give you back the ">" prompt.
Tip: Canceling commands
If you're using R from the command line instead of from within RStudio, you need to use Ctrl+C instead of Esc to cancel the command. This applies to Mac users as well!
Canceling a command isn't only useful for killing incomplete commands: you can also use it to tell R to stop running code (for example if it's taking much longer than you expect), or to get rid of the code you're currently writing.
Source: The Carpentries, https://swcarpentry.github.io/r-novice-gapminder/01-rstudio-intro/index.html
This work is licensed under a Creative Commons Attribution 4.0 License.