R is a popular programming language used for statistical computing and graphical presentation.
Its most common use is to analyze and visualize data.
To install R, go to https://cloud.r-project.org/ and download the latest version of R for Windows, Mac or Linux.
When you have downloaded and installed R, you can run R on your computer.
After installation of R
If you type 5 + 5, and press enter, you will see that R outputs 10.
5+5
## [1] 10
To output text in R, use single or double quotes:
"Hello World!"
## [1] "Hello World!"
To output numbers, just type the number (without quotes):
5
## [1] 5
10
## [1] 10
25
## [1] 25
To do simple calculations, add numbers together:
10-7
## [1] 3
Variables are containers for storing data values.
R does not have a command for declaring a variable. A variable is created the moment you first assign a value to it. To assign a value to a variable, use the <- sign (or = sign). To output (or print) the variable value, just type the variable name:
name <- "Bijay Lal Pradhan"
age <- 50
name # output "Bijay Lal Pradhan"
## [1] "Bijay Lal Pradhan"
age # output 50
## [1] 50
You can also concatenate, or join, two or more elements, by using the paste() [or cat] function.
To combine both text and a variable, R uses comma (,):
text <- "awesome"
paste("R is", text)
## [1] "R is awesome"
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for R variables are: A variable name must start with a letter and can be a combination of letters, digits, period(.) and underscore(). If it starts with period(.), it cannot be followed by a digit. A variable name cannot start with a number or underscore () Variable names are case-sensitive (age, Age and AGE are three different variables) Reserved words cannot be used as variables (TRUE, FALSE, NULL, if…)
Basic data types in R can be divided into the following types:
numeric - (10.5, 55, 787)
integer - (1L, 55L, 100L, where the letter “L” declares this as an integer)
complex - (9 + 3i, where “i” is the imaginary part)
character (a.k.a. string) - (“k”, “R is exciting”, “FALSE”, “11.5”)
logical (a.k.a. boolean) - (TRUE or FALSE)
We can use the class() function to check the data type of a variable:
# numeric
x <- 10.5
class(x)
## [1] "numeric"
# integer
x <- 1000L
class(x)
## [1] "integer"
# complex
x <- 9i + 3
class(x)
## [1] "complex"
# character/string
x <- "R is exciting"
class(x)
## [1] "character"
# logical/boolean
x <- TRUE
class(x)
## [1] "logical"
1.3.0.1 Comments
Comments can be used to explain R code, and to make it more readable. It can also be used to prevent execution when testing alternative code.
Comments starts with a #. When executing code, R will ignore anything that starts with #.
This example uses a comment before a line of code: