Test if Data Object is a Vector in R (2 Examples)
In this post you’ll learn how to check whether a data object is a vector in the R programming language.
The page will consist of these contents:
Let’s just jump right in!
Creation of Example Data
To begin with, we’ll need to create some example data:
my_vec <- 1:5 # Create example vector my_vec # Print example vector #  1 2 3 4 5
The previous output of the RStudio console shows that the example data is a vector object containing five elements.
If we now apply the is.vector function to this data object, the logical value TRUE is returned:
is.vector(my_vec) # Apply is.vector function to vector #  TRUE
However, there’s a problem with this procedure. Let’s illustrate that by creating a list object:
my_list <- list(1:3, # Create example list "x") my_list # Print example list # [] #  1 2 3 # # [] #  "x"
If we now apply the is.vector function to this list, an unexpected output is returned:
is.vector(my_list) # Apply is.vector function to list #  TRUE
Surprisingly, the previous output has returned the logical value TRUE once again, even though we have applied the is.vector function to a list object.
How can we avoid this surprising result? This is what I will show next!
Example 1: Apply is.vector() & is.atomic() Functions to List Object
The following R programming syntax illustrates how to properly test whether a data object is a vector.
For this task, we have to apply the is.vector function in combination with the is.atomic function. Have a look at the R code below:
is.vector(my_list) && is.atomic(my_list) # Apply is.vector & is.atomic #  FALSE
This time, the logical value FALSE was returned, i.e. the expected result.
Example 2: Apply is.vector() & is.atomic() Functions to Vector Object
We may also apply our combined functions to a real vector object:
is.vector(my_vec) && is.atomic(my_vec) #  TRUE
The value TRUE is printed – great!
Video & Further Resources
Do you need more information on the R programming code of this article? Then I can recommend watching the following video on my YouTube channel. In the video, I illustrate the examples of this tutorial in a live session.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may read some of the other tutorials on this homepage. A selection of tutorials about related topics such as vectors, data objects, extracting data, and character strings can be found below:
- Order Data Frame Rows According to Vector
- Select Data Frame Rows based on Values in Vector
- Select Data Frame Column Using Character Vector in R
- Access Attributes of Data Object
- R Programming Overview
Summary: This article has illustrated how to test whether a data object is a vector in R. In case you have further questions, let me know in the comments below.
Statistics Globe Newsletter