Error: ‘list’ object cannot be coerced to type ‘double’

Error: ‘list’ object cannot be coerced to type ‘double’, as the first step, we’ll need to generate some data that we’ll later use in the examples.

List <- list(1:5,10,10:20)
List
[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 10

[[3]]
 [1] 10 11 12 13 14 15 16 17 18 19 20

The structure of our example data is shown in the previous RStudio console output: It’s a list with three numeric list entries in it.

Principal Component Analysis in R » finnstats

Example 1 Reproducing Error: ‘list’ object cannot be coerced to type ‘double’

When lists are transformed into vectors or arrays, this section shows a common error message.

Let’s see the wrong code and reproduce the error message.

as.numeric(List)
Error: 'list' object cannot be coerced to type 'double'

As you can see, the error message from the RStudio console is: (list) object cannot be converted to type ‘double’.

The reason for this is that we can’t use the as.numeric function on a list with multiple list components.

After that, we’ll show you how to correct the problem. So don’t stop reading!

Example 2: Appropriate R Code for List to Numeric Vector Conversion

In R, Example 2 shows how to properly convert a list to a numeric vector. Look at the R code below.

Now we can apply to unlist and convert into as.numeric

as.numeric(unlist(List))    
[1]  1  2  3  4  5 10 10 11 12 13 14 15 16 17 18 19 20

As you can see, we combined the unlist and as.numeric functions, which means we first converted our list to a vector and then converted that vector to numeric. Everything is in order!

Power analysis in Statistics with R » finnstats

You may also like...

Leave a Reply

Your email address will not be published.