R Programming
R Programming
R Programming
R programming is popular in the field of data science among data analysts, researchers,
statisticians, etc. You can use R to retrieve data from datasets, clean them, analyze and
visualize them, and present them in the most suitable way.
R Comments
Comments are portions of a computer program that are used to describe a
piece of code.Comments have nothing to do with code logic. They do not get
interpreted or compiled and are completely ignored during the execution of the
program.
. R Single-Line Comments
You use the # symbol to create single-line comments in R. For example,
2. R Multi-Line Comments
As already mentioned, R does not have any syntax to create multi-line
comments.
. Boolean Variables
It stores single bit data which is either TRUE or FALSE. Here, TRUE means yes
and FALSE means no.
2. Integer Variables
4. Character Variables
It stores a single character data. For example
5. String Variables
It stores data that is composed of more than one character. We use double
quotes to represent string data.
R Constants
Constants are those entities whose values aren't meant to be changed
anywhere throughout the code. In R, we can declare constants using the <-
symbol
Types of R Constants
In R, we have the following types of constants.
1. Integer Constants
Integer constants are the integer values we use in our code. These constants
end with the letter L.
2. Numeric Constants
In R programming, numeric constants can be integers (4), floating-point
numbers (0.55), or exponential numbers (3e-3).
3. Logical Constants
4. String Constants
5. Complex Constants
Special R Constants
R programming also provides 4 special types of constants.
R Data Types
A variable can store different types of values such as numbers, characters etc.
These different types of data that we can use in our code are called data
types.
The logical data type in R is also known as boolean data type. It can only
have two values: TRUE and FALSE
In R, the numeric data type represents all real numbers with or without decimal
values
The integer data type specifies real values without decimal points. We use the
suffix L to specify integer data.
The complex data type is used to specify purely imaginary values in R. We use
the suffix i to specify the imaginary part
R print() Function
In R, we use the print() function to print values and variables
paste() Function in R
You can also print a string and variable together using the print() function.
For this, you have to use the paste() function inside print().
Notice the use of the paste() function inside print(). The paste() function
takes two arguments:
R sprintf() Function
The sprintf() function of C Programming can also be used in R. It is used to
print formatted strings.
R Numbers
Numbers in R can be divided into 3 different categories:
● Numeric: It represents both whole and floating-point numbers. For
example, 123, 32.43, etc.
● Integer: It represents only whole numbers and is denoted by L. For
example, 23L, 39L, etc.
● Complex: It represents complex numbers with imaginary parts. The
imaginary parts are denoted by i. For example, 2 + 3i, 5i, etc.
R if Statement
x <- 3
if (x > 0) {
print("Outside if statement")
R if...else Statement
age <- 15
R while Loop
while loops are used when you don't know the exact number of times a
block of code is to be repeated
number = 1
# increment number by 1
number = number + 1
# break if number is 6
if (number == 6) {
break
}
}
R for Loop
A for loop is used to iterate over a list, vector or any other object of elements.
The syntax of for loop is:
# vector of numbers
num = c(2, 3, 12, 14, 5, 19, 23, 64)
# check if i is even
if (i %% 2 == 0) {
count = count + 1
}
}
print(count)
R Functions
Introduction to R Functions
A function is just a block of code that you can call and run from any part of
your program. They are used to break our code in simple parts and avoid
repeatable codes.
You can pass data into functions with the help of parameters and return some
other data as a result. You can use the function() reserve keyword to create a
function in R. The syntax is:
Named Arguments
# define a function to compute power
power(b=3, a=2)
Return Values
You can use the return() keyword to return values from a function. For
example,
# define a function to compute power
return (a^b)
return (a^b)
return (exponent)
print(result(3))
R Strings
A string is a sequence of characters. For example, "Programming" is a string
that includes characters: P, r, o, g, r, a, m, m, i, n, g.
In R, we represent strings using quotation marks (double quotes, " " or single
quotes, ' ').
message2 <- "Welcome to Programiz"
print(message2)
R Vectors
A vector is the basic data structure in R that stores data of similar types
Create a Vector in R
In R, we use the c() function to create a vector
print(employees)
Numeric Vector in R
● # a vector with number sequence from 1 to 5
● numbers <- c(1, 2, 3, 4, 5)
●
● print(numbers)
print(number)
Length of Vector in R
We can use the length() function to find the number of elements present
inside the vector.
Create a Matrix in R
In R, we use the matrix() function to create a matrix.
# create a 2 by 3 matrix
print(matrix1)
print(matrix1)
In R, we can also access the entire row or column based on the value passed
inside [].
print(matrix1)
matrix1[1,2] = 140
print(total1)
print(total2)
R List
A List is a collection of similar or different types of data.
print(list1[1]) # 24
print(list1)
append(list1, 3.14)
Length of R List
In R, we can use the length() function to find the number of elements present
inside the list. For example,
R Array
An Array is a data structure which can store data of the same type in more
than two dimensions.
Create an Array in R
In R, we use the array() function to create an array.
Here,
print(array1)
In R, we can also access the entire row or column based on the value passed
inside [].
For example,
print(array1)
R Data Frame
A data frame is a two-dimensional data structure which can store data in
tabular format.
Data frames have rows and columns and each column can be a different
vector. And different vectors can be of different data types.
print(dataframe1)
print(dataframe1[1])
print(dataframe1[["Name"]])
print(dataframe1$Name)
If we want to combine two data frames vertically, the column name of the two
data frames must be the same. For example,
print(updated)
cbind()
# create a data frame
Suppose a data field such as marital status may contain only values from
single, married, separated, divorced, or widowed.
Create a Factor in R
In R, we use the factor() function to create a factor. Once a factor is created,
it can only contain predefined set values called levels.
factor(vector)
# create a factor
print(students_gender)
# create a factor
students_gender <- factor(c("male", "female", "male", "transgender",
"female"))
print(students_gender[1])
print(students_gender[4])
R Bar Plot
Bar Plots is one of the most efficient ways of representing datas. It can be
used to summarize large data in visual form.
Bar graphs have the ability to represent data that shows changes over time,
which helps us to visualize trends.
ylab = "Day",
print(result)
Output
R Pie Chart
A pie chart is a circular statistical graphic, which is divided into slices to
illustrate numerical proportion.
Pie charts represents data visually as a fractional part of a whole, which can
be an effective communication tool.
print(result)
Output