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 #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 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 #convert list to numeric x_num 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.
Additional Resources
The following tutorials explain how to troubleshoot other common errors in R:
How to Fix in R: names do not match previous names
How to Fix in R: contrasts can be applied only to factors with 2 or more levels
How to Fix in R: longer object length is not a multiple of shorter object length