R offers several helpful built‑in functions that allow you to examine vector objects. These functions tell you how many elements a vector has, what type of data it stores, and how R handles that data internally. Understanding these functions is important when working with datasets, debugging code, or verifying the structure of your objects.
Understanding Functions That Operate on Vectors
Below are the most commonly used functions that help you inspect and understand vector objects in R.
1. length ( ) – Count the Number of Elements
The length ( ) function simply tells you how many items are present in a vector.
length(my_vec1)
Output:
3
This means the vector contains 3 elements. This function is very useful when checking dataset sizes or validating input values.
2. class ( ) – Identify the Data Type Category
The class ( ) function shows the type of data stored in the vector.
class(my_vec1)
class(my_vec2)
class(my_vec3)
Expected Output:
'integer'
'integer'
'numeric'
Explanation:
- my_vec1 is an integer vector
- my_vec2, created using
1:3, is also an integer vector - my_vec3, created using
seq(), becomes a numeric vector becauseseq()generates decimal numbers by default
This function helps you confirm whether the data type is what you expect before performing calculations.
3. typeof ( ) – Check the Internal Storage Type
The typeof ( ) function reveals how R stores the values internally.
typeof(my_vec3)
Output:
'double'
This means the values inside the vector are stored as double‑precision numbers. Even if the vector appears as numeric, the underlying storage mode may be different.
- class ( ) = numeric → describes the category of data
- typeof ( ) = double → describes the internal representation
This difference becomes important in memory management and when working with large datasets.
4. str ( ) – Display the Full Structure of the Vector
The str ( ) function is one of the most powerful tools in R for inspecting objects. It displays:
- the type of object
- how many elements it has
- the actual values stored inside
str(my_vec3)
Output:
num [1:3] 1 2 3
This tells us:
- The vector is numeric (
num) - It contains three elements (
[1:3]) - The values are 1, 2, and 3
This function is extremely useful for checking data structures when you import datasets, read files, or work with large data frames.
Why These Functions Matter
These functions help you avoid errors, understand your data clearly, and ensure that calculations are performed correctly. When working on data cleaning, statistical modelling, or machine learning tasks, these basic checks save time and prevent mistakes.
Once you master these vector inspection functions, working with larger and more complex R objects becomes much easier.