(list) object cannot be coerced to type ‘double’ – R Error

Total
0
Shares

R-language throws error (list) object cannot be coerced to type ‘double‘ when we try to convert a list of string or other type values to a numeric vector.

To correctly coerce a list, you should unlist it first and then convert into numeric vector.

a <- structure(list(`X$Days` = c("10", "38", "66", "101", "129", "185", "283","374")), .Names = "X$Days")
as.numeric(unlist(a))

There are different types of objects in R which could be coerced during computations. Some of these objects are –

"NULL" NULL
"symbol" a variable name
"pairlist" a pairlist object (mainly internal)
"closure" a function
"environment" an environment
"promise" an object used to implement lazy evaluation
"language" an R language construct
"special" an internal function that does not evaluate its arguments
"builtin" an internal function that evaluates its arguments
"char" a ‘scalar’ string object (internal only) ***
"logical" a vector containing logical values
"integer" a vector containing integer values
"double" a vector containing real values
"complex" a vector containing complex values
"character" a vector containing character values
"..." the special variable length argument ***
"any" a special type that matches all types: there are no objects of this type
"expression" an expression object
"list" a list
"bytecode" byte code (internal only) ***
"externalptr" an external pointer object
"weakref" a weak reference object
"raw" a vector containing bytes
"S4" an S4 object which is not a simple object

Some other examples of coercion are –

> labs <- paste(c("X","Y"), 1:10, sep="")
c("X1", "Y2", "X3", "Y4", "X5", "Y6", "X7", "Y8", "X9", "Y10")

Here we used paste() function which takes an arbitrary number of arguments and concatenates them one by one into character strings. So, they are coerced into characters.

According to R manuals

A list whose components conform to the restrictions of a data frame may be coerced into a data frame using the function as.data.frame()

    Tweet this to help others

Live Demo

Open Live Demo