How to Solve R Error: list object cannot be coerced to type double

by | Programming, R, Tips

This error occurs if you try to convert the elements of a list to numeric without converting the list to a vector using unlist().

You can solve this error by using the unlist() function before calling the numeric() function, for example,

num <- as.numeric(unlist(x))

This tutorial will go through the error and how to solve it with code examples.


Table of contents

Example

Consider the following example of a list containing strings.

x <- list(c("10", "38", "66", "101", "129", "185", "283", "374"))
x
[1] "10"  "38"  "66"  "101" "129" "185" "283" "374"

We want to convert the elements in the list to numeric. Let’s attempt to convert the elements using as.numeric().

x_num <- as.numeric(x)

Let’s run the code to see what happens:

Error: 'list' object cannot be coerced to type 'double'

The error occurs because we cannot use a list as an argument to the numeric() function. We can verify the object x is a list using the class() function:

class(x)
[1] "list"

Solution

The unlist function converts a list to a vector. The as.numeric() function accepts vector as an argument. We can use the unlist() function to solve this error. Let’s look at the revised code:

num <- as.numeric(unlist(x))
num

Let’s run the code to see the result:

[1]  10  38  66 101 129 185 283 374

We can verify that num is a vector of numeric values:

class(num)
[1] "numeric"

Summary

Congratulations on reading to the end of this tutorial!

For further reading on R related errors, go to the articles: 

Go to the online courses page on R to learn more about coding in R for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨