Learn about data types and their importance in a programming language. More specifically, learn how to use various data types like vector, matrices, lists, and dataframes in the R programming language.
Before we start with the introduction and learn about various data types in R, let's quickly set up the R environment both on the Terminal and Jupyter Notebook.
Once the above two commands are successful, run jupyter from the terminal and open a notebook with R kernel as shown below:
Now you are all set to write your first R code on jupyter notebook.
Introduction
To make use of R to the fullest, it is very important to know and understand various data types and data structures that exist in R and how they function. They play a key role in almost all problems and especially when you are working on machine learning problems, which are very data-centric.
In a programming language, we usually need variables to store information, which can be an integer, character, floating-point, boolean, etc. The type of the variable is purely based on which kind of information it holds. If it is assigned an integer, then the variable has a data type as int. Variables are merely reserved memory locations at which values are stored. As soon as you create a variable, some memory space is reserved for it.
Based on the data type of a variable, some memory will be allocated by the operating system. For example, in R programming, a variable that holds an integer will reserve a memory of 4 bytes and 1 byte for a character.
Programming languages like C, C++, and Java, variables are declared as data type; however, in Python and R, the variables are an object. Objects are nothing but a data structure having few attributes and methods which are applied to its attributes.
There are various kinds of R-objects or data structures which will be discussed in this tutorial like:
Integer: Numbers that do not contain decimal values have a data type as an integer. However, to create an integer data type, you explicitly use as.integer() and pass the variable as an argument.
Character: As the name suggests, it can be a letter or a combination of letters enclosed by quotes is considered as a character data type by R. It can be alphabets or numbers.
Factor: They are a data type that is used to refer to a qualitative relationship like colors, good & bad, course or movie ratings, etc. They are useful in statistical modeling.
To achieve this, you will make use of the c() function, which returns a vector (one-dimensional) by combining all the elements.
fac <- factor(c("good","bad","ugly","good","bad","ugly"))
Before moving forward, let us understand a couple of important tips that can come in handy!
Always remember that R programming language is case-sensitive. All of the objects that are defined above should be used in the same manner, be it upper or lower, as shown in the example below.
Unlike vectors, a list can contain elements of various data types and is often known as an ordered collection of values. It can contain vectors, functions, matrices, and even another list inside it (nested-list).
Lists in R are one-indexed, i.e., the index starts with one.
Let's understand the concept of lists with a quick example that will have three different types of data types stored in one list.
Let's access each vector in the list separately. To achieve this, you will use double square brackets since the three vectors are placed on one level inside the list. python
combined_list[[1]]
Finally, let's try to flatten the list. One important thing to remember is that since combined_list is a combination of character and numeric datatype, the character data type will get the precedence, and the data type of complete list will become a character.
Vectors are an object which is used to store multiple information or values of the same data type. A vector can not have a combination of both integer and character. For example, if you want to store 100 students' total marks, instead of creating 100 different variables for each student, you would create a vector of length 100, which will store all the student marks in it.
A vector can be created with a function c(), which will combine all the elements and return a one-dimensional array.
Let's create a vector marks with data of five students of class numeric.
Similar to a vector, a matrix is used to store information about the same data type. However, unlike vectors, matrices are capable of holding two-dimensional information inside it.
Unlike a matrix, Data frames are a more generalized form of a matrix. It contains data in a tabular fashion. The data in the data frame can be spread across various columns, having different data types. The first column can be a character while the second column can be an integer, and the third column can be logical.
The variables or features are in columnar fashion, also known as a header, while the observations are in rows with the first element being the name of the row followed by the actual data, also known as data rows.
DataFrame can be created using the data.frame() function.
DataFrame has been widely used in the reading comma-separated files (CSV), text files. Their use is not only limited to reading the data, but you can also use them for machine learning problems, especially when dealing with numerical data. DataFrames can be useful for understanding the data, data wrangling, plotting and visualizing.
Let's create a dummy dataset and learn some data frame specific functions.
dataset <- data.frame(
Person = c("Aditya","Ayush","Akshay"),
Age = c(26,26,27),
Weight = c(81,85,90),
Height = c(6,5.8,6.2),
Salary = c(50000,80000,100000))
Let's look at the head function which is very useful when you have millions of records and you want to look at only the first few rows of your data. Similarly, the tail function will output the last few rows of your data.
'data.frame':3 obs.of5variables:
$ Person: Factor w/3 levels "Aditya","Akshay",..:132
$ Age : num 262627
$ Weight: num 818590
$ Height: num 65.86.2
$ Salary: num 5e+048e+041e+05
Now let's look at the summary() function, which comes in handy when you want to understand the statistics of your dataset. As shown below, it divides your data into three quartiles, based on which you can get some intuition about the distribution of your data. It also shows if there are any missing values in your dataset.
This tutorial was a good starting point for beginners who are curious to learn the R programming language. As a good exercise, feel free to check out more helper functions related to each data type.
There is a lot of information related to R that remains unraveled like Conditionals and Control Flow in R, Utilities in R, and the most exciting one Machine Learning using R, which will be covered in the future tutorials, so stay tuned!
Please feel free to ask any questions related to this tutorial in the comments section below.
Learn all about R's matrix, naming rows and columns, accessing elements also with computation like addition, subtraction, multiplication, and division.
Learn about several useful functions for data structure manipulation, nested-lists, regular expressions, and working with times and dates in the R programming language.
Before we start with the introduction and learn about various data types in R, let's quickly set up the R environment both on the Terminal and Jupyter Notebook.
The following command is for Mac operating system, which will install R on your terminal.
To verify the installation has been successful, just type R (upper-case) in the terminal, and you will enter into an R session, as shown below.
For installation on other operating systems, feel free to check this tutorial.
Now let's add R programming language as a kernel on jupyter notebook. Make sure you have jupyter notebook already installed on your system.
Go to your terminal and open the R session and enter the below two commands, which will add the R kernel to your jupyter notebook.
Once the above two commands are successful, run jupyter from the terminal and open a notebook with R kernel as shown below:
Now you are all set to write your first R code on jupyter notebook.
Introduction
To make use of R to the fullest, it is very important to know and understand various data types and data structures that exist in R and how they function. They play a key role in almost all problems and especially when you are working on machine learning problems, which are very data-centric.
In a programming language, we usually need variables to store information, which can be an integer, character, floating-point, boolean, etc. The
typeof the variable is purely based on which kind of information it holds. If it is assigned an integer, then the variable has a data type asint. Variables are merely reserved memory locations at which values are stored. As soon as you create a variable, some memory space is reserved for it.Based on the data type of a variable, some memory will be allocated by the operating system. For example, in R programming, a variable that holds an integer will reserve a memory of 4 bytes and 1 byte for a character.
Programming languages like C, C++, and Java, variables are declared as data type; however, in Python and R, the variables are an object. Objects are nothing but a data structure having few attributes and methods which are applied to its attributes.
There are various kinds of R-objects or data structures which will be discussed in this tutorial like:
Vectors
Lists
Matrices
Arrays
Factors
Data Frames
Let's first understand some of the basic datatypes on which the R-objects are built like Numeric, Integer, Character, Factor, and Logical.
You can check the data type of
ausing keywordclass().as.integer()and pass the variable as an argument.To achieve this, you will make use of the
c()function, which returns a vector (one-dimensional) by combining all the elements.The
facfactor has three levels as good, bad, and ugly, which can be checked using the keywordlevels, and the type of level will be a character.Before moving forward, let us understand a couple of important tips that can come in handy!
ls(), as shown below.Lists
Unlike vectors, a list can contain elements of various data types and is often known as an ordered collection of values. It can contain vectors, functions, matrices, and even another list inside it (nested-list).
Lists in R are one-indexed, i.e., the index starts with one.
Let's understand the concept of lists with a quick example that will have three different types of data types stored in one list.
Levels:
Levels:
Let's access each vector in the list separately. To achieve this, you will use
double square bracketssince the three vectors are placed on one level inside the list.python combined_list[[1]]python combined_list[[2]]Levels:
Now, let us try to access the fifth element from the third vector, which gives the letter
e.Finally, let's try to flatten the list. One important thing to remember is that since
combined_listis a combination ofcharacterandnumericdatatype, thecharacterdata type will get the precedence, and the data type of complete list will become acharacter.Vectors
Vectors are an object which is used to store multiple information or values of the same data type. A vector can not have a combination of both integer and character. For example, if you want to store 100 students' total marks, instead of creating 100 different variables for each student, you would create a vector of length 100, which will store all the student marks in it.
A vector can be created with a function
c(), which will combine all the elements and return a one-dimensional array.Let's create a vector
markswith data of five students of classnumeric.Let us check the length of the vector, which should return the number of elements contained in it.
Now, let's try to access a specific element by its index.
<NA>
Slicing: Similar to Python, the concept of slicing can be applied in R as well.
Let's try to access elements from second to fifth using slicing.
Let's now create a
charactervector that is similar to creating a numeric character.'character'
If we create a vector that has both numeric and character values, the numeric values will get converted to a character data type.
Let's create a vector with 1024 numeric values with the help of a slicing concept.
Now, try to access the middle and the last element. To do that, you will use the
lengthfunction.To create a vector of odd numbers, you can use the function
seq, which takes in three parameters: start, end, and step size.Matrix
Similar to a vector, a matrix is used to store information about the same data type. However, unlike vectors, matrices are capable of holding two-dimensional information inside it.
The syntax of defining a matrix is:
byrow=TRUEsignifies that the matrix should be filled by rows.byrow=FALSEindicates that the matrix should be filled by columns (the default).Let's quickly define a matrix
Mof shape $2\times3$.Let's use the slicing concept and fetch elements from a row and column.
DataFrame
Unlike a matrix, Data frames are a more generalized form of a matrix. It contains data in a tabular fashion. The data in the data frame can be spread across various columns, having different data types. The first column can be a character while the second column can be an integer, and the third column can be logical.
The variables or features are in columnar fashion, also known as a
header, while the observations are in rows with the first element being the name of the row followed by the actual data, also known asdata rows.DataFrame can be created using the
data.frame()function.DataFrame has been widely used in the reading comma-separated files (CSV), text files. Their use is not only limited to reading the data, but you can also use them for machine learning problems, especially when dealing with numerical data. DataFrames can be useful for understanding the data, data wrangling, plotting and visualizing.
Let's create a dummy dataset and learn some data frame specific functions.
Let's look at the
headfunction which is very useful when you have millions of records and you want to look at only the first few rows of your data. Similarly, thetailfunction will output the last few rows of your data.Now let's look at the
summary()function, which comes in handy when you want to understand the statistics of your dataset. As shown below, it divides your data into three quartiles, based on which you can get some intuition about the distribution of your data. It also shows if there are any missing values in your dataset.Conclusion
Congratulations on finishing the tutorial.
This tutorial was a good starting point for beginners who are curious to learn the R programming language. As a good exercise, feel free to check out more helper functions related to each data type.
There is a lot of information related to R that remains unraveled like Conditionals and Control Flow in R, Utilities in R, and the most exciting one Machine Learning using R, which will be covered in the future tutorials, so stay tuned!
Please feel free to ask any questions related to this tutorial in the comments section below.
If you would like to learn more about R, take DataCamp's Intermediate R course and check out the Introduction to Data frames in R tutorial.