Introduction
Learning Objectives:
Familiarize with RStudio interface
Use interactive console and code editor
Assignment statement
Hello world
Save R program and R data files
Add comment to your code
Interactive console
In the interactive console located at the bottom left window in RStudio, we can see the > symbol. If you type a command and press return, R will evaluate it and print the result for you.
To start, let us try to use it as a calculator.
6 + 9
## [1] 15
7-4
## [1] 3
3*9
## [1] 27
Code Editor
Code editor is located at the top left window in RStudio. If it is not shown you can *File > New File > R Script.
In the code editor, type the code and click``Run’’ on the top right of the window. Then you can see the code will be copied to the interactive console.
Assignment
The left is assigned to the value on the right. For example, x - 15 implies that the value 15 is assigned to a variable called x. Note: Variables are case-sensitive.
x <- 15
x -1
## [1] 14
Hello World
To print an output, simply use the function print()
print('Hello Word!')
## [1] "Hello Word!"
Sometimes we would also want to display the value of a variable:
x <- 4
y <- 5
z <- x+y
print(z)
## [1] 9
However, we want to print the description of the variable too. Then we have to use function cat() to combine description and output.
x <- 4
y <- 5
cat('The sum of x and y is', x+y)
## The sum of x and y is 9
Script and Data Files
Script files have file association .R while the data can be stored in .RData.
To save and open .R file, simply save and open using the RStudio.
To save and open RData file, we have the following code:
save.image("XXX.Rdata")
load("XXX.Rdata")
Readability
Comment is important to improve readability for other users (and for yourself in a few weeks later!).
# A single line comment begins
Spacing is also important. Try not to make your code packed together.
Another tips is to use indentation. A short cut is Ctrl + I in RStudio.