Data Structures in R are basically the elements used for storing multiple types of data. Basic data structures in R are vectors, lists, matrices, data frames, and factors. Let’s have a look at all the different types of data structures one by one with an example.
Vectors are the most basic type of data structure in R. Basically it has the same type of data elements in a sequence. Vectors can be created by using c() function like you can see in this example below:
You can see the image above of the vector we created with the name “vector1”, containing values from 1 to 5 using c() function:
Vectors are not limited to just numbers, we can also create vectors with characters in it by using double quotes for each value, as you can see above.
Now let’s have a look at lists. Lists contain elements of different data types – like strings, numbers, matrix, vectors, etc. They are very similar to vectors, but lists can store values of any data types, unlike vectors.
We can create lists using list() function as you can see in this image below:
The above-created list named “newlist” contains 8 items which include: 3 characters, 3 numbers, and 2 vectors.
Data frames store data in two dimensions i.e. rows and columns. It is similar to lists, which means it can store values of different data types. But it can store values of the same type only in a column. For eg: Numbers and words cannot be stored in the same column or a single column.
Below you can see a data frame named “Customer_info” created using 2 different vectors named “Customer_name” and “Customer_info” :
We would be able to see a data frame with 2 columns and 5 rows when we will run the code mentioned above.
A matrix is basically a mixture of a vector and a data frame. Like a vector, it can store values of only one data type and it can store values and represent data in a table format of rows and columns only, like a data frame.
Here’s how we can create a matrix, using the matrix() function:
We can see above a matrix named “mymatrix” with 2 columns and 5 rows.