RStudio is one of the most popular environment for R programming. Download and install it from http://www.rstudio.com/download.
When you open RStudio, you will be seeing the console screen, which would look like:
We will be typing the codes in the line with >, and you will get an output after [#], where # is the number that specifies the order of the code. For example:
1+1
## [1] 2
This [1] means that this is the first code that it was written.
This will not save the code that you wrote, so you can alternatively open a new R script, and type the codes there. To run the code, go to the line and press Ctrl + Enter. TYou can alternatively, press the Run button at the top right side of the screen. You will then see the output in the console screen.
As a beginning, we will cover the basics of math operations.
R can do all math operations:
| Operation | Meaning |
|---|---|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
For example:
1 + 2
## [1] 3
2 * 4
## [1] 8
1 - 4
## [1] -3
6 / 2
## [1] 3
Objects are very important in R programming. You can assign a value to the object by using <-. For example,
a <- 1
The code above substitutes 1 into an object a.
a
## [1] 1
We can do all operations with objects. For example:
a <- 5
a * 2
## [1] 10
day1 <- 10
day2 <- 4
day1 + day2
## [1] 14
We can use
print()
to print out the object inside (). FOr example:
number <- 1
print(number)
## [1] 1
However, we can also return the output of the object without print(), and it is often omitted in programming:
number <- 1
# Write number object without print()
number
## [1] 1
©2021 by Daiki Tagami. All rights reserved.
4. Comments
We can add comments in R codes by using
#. R won’t recognize all the things that you wrote afterwards, so you can add some explanations to the code through comments. For example:Throughout this R lab, I will be adding some explanations inside the code by using comments.