Error: Coerce List Object to Type Double in R (2 Examples)
In this tutorial you’ll learn how to convert a list to a numeric vector in R.
Table of contents:
Here’s how to do it!
Creation of Example Data
As a first step, we have to create some data that we can use in the examples later on:
my_list <- list(1:3, # Example list 5, 10:15) my_list # Print list # [] #  1 2 3 # # [] #  5 # # [] #  10 11 12 13 14 15
The previous RStudio console output shows the structure of our example data: It’s a list containing three numeric list elements.
Example 1: Reproducing Error: (list) object cannot be coerced to type ‘double
This Section illustrates a typical error message, when lists are converted to vectors or arrays. Have a look at the following R code:
as.numeric(my_list) # Wrong R code # Error: (list) object cannot be coerced to type 'double'
As you can see, the RStudio console returns the error message: (list) object cannot be coerced to type ‘double’
The reason is that we cannot simply apply the as.numeric function to a list containing multiple list elements.
Next, I’ll explain how to fix this error. So keep on reading!
Example 2: Appropriate R Code for Conversion of List to Numeric Vector
Example 2 explains how to adequately convert a list to a numeric vector in R. Have a look at the following R code:
as.numeric(unlist(my_list)) # Apply unlist & as.numeric # 1 2 3 5 10 11 12 13 14 15
As you have seen, we used a combination of the unlist and as.numeric functions, i.e. first we are converting our list to a vector and then we convert this vector to numeric. Works smoothly!
Video & Further Resources
Do you need further info on the R programming syntax of this article? Then you might want to have a look at the following video of my YouTube channel. In the video tutorial, I show the examples of this article in RStudio.
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.
Additionally, I can recommend to read the other tutorials of my website.
- The unlist Function in R
- Convert List of Vectors to Data Frame
- Convert Vector to List
- Convert Data Frame Rows to List
- Select First Element of Nested List
- message, warning & stop Functions in R
- The R Programming Language
In this R programming tutorial you learned how to convert lists to arrays. In case you have additional comments and/or questions, don’t hesitate to let me know in the comments section.