Table of Contents
This error occurs when attempting to convert an object, such as a string or a list, into a double data type. To fix this problem, the object must be converted into a compatible data type, such as a number, before it can be converted into a double data type. In some cases, the object may need to be modified to be compatible, such as changing a string to a number, before it can be converted.
One common error you may encounter in R is:
Error: (list) object cannot be coerced to type 'double'
This error occurs when you attempt to convert a list of multiple elements to numeric without first using the unlist() function.
This tutorial shares the exact steps you can use to troubleshoot this error.
How to Reproduce the Error
The following code attempts to convert a list of multiple elements to numeric:
#create list x <- list(1:5, 6:9, 7) #display list x [[1]] [1] 1 2 3 4 5 [[2]] [1] 6 7 8 9 [[3]] [1] 7 #attempt to convert list to numeric x_num <- as.numeric(x) Error: (list) object cannot be coerced to type 'double'
Since we didn’t use the unlist() function, we received the (list) object cannot be coerced to type ‘double’ error message.
How to Fix the Error
To convert the list to numeric, we need to ensure that we use the unlist() function:
#create list x <- list(1:5, 6:9, 7) #convert list to numeric x_num <- as.numeric(unlist(x)) #display numeric values x_num [1] 1 2 3 4 5 6 7 8 9 7
We can use the class() function to verify that x_num is actually a vector of numeric values:
#verify that x_num is numeric
class(x_num)
[1] "numeric"
We can also verify that the original list and the numeric list have the same number of elements:
#display total number of elements in original list sum(lengths(x)) [1] 10 #display total number of elements in numeric list length(x_num) [1] 10
We can see that the two lengths match.
How to Fix in R: longer object length is not a multiple of shorter object length