The code:
a <- structure(list(`X$Days` = c("10", "38", "66", "101", "129", "185", "283",
"374")), .Names = "X$Days")
Then a is like
$`X$Days`
[1] "10" "38" "66" "101" "129" "185" "283" "374"
I would like to coerce a to an array of numeric values, but coercing functions return me
Error: (list) object cannot be coerced to type 'double'
Thanks,
asked Sep 12, 2012 at 8:29
If you want to convert all elements of a to a single numeric vector and length(a) is greater than 1 (OK, even if it is of length 1), you could unlist the object first and then convert.
as.numeric(unlist(a))
# [1] 10 38 66 101 129 185 283 374
Bear in mind that there aren’t any quality controls here. Also, X$Days a mighty odd name.
answered Sep 12, 2012 at 8:39
BenBarnesBenBarnes
18.9k6 gold badges56 silver badges73 bronze badges
5
If your list as multiple elements that need to be converted to numeric, you can achieve this with lapply(a, as.numeric).
answered Sep 12, 2012 at 8:41
Matthew PlourdeMatthew Plourde
43.3k6 gold badges93 silver badges113 bronze badges
1
You can also use list subsetting to select the element you want to convert. It would be useful if your list had more than 1 element.
as.numeric(a[[1]])
answered May 22, 2015 at 17:44
USER_1USER_1
2,3691 gold badge27 silver badges28 bronze badges
In this case a loop will also do the job (and is usually sufficiently fast).
a <- array(0, dim=dim(X))
for (i in 1:ncol(X)) {a[,i] <- X[,i]}
answered Oct 1, 2018 at 13:10
There are problems with some data. Consider:
as.double(as.character("2.e")) # This results in 2
Another solution:
get_numbers <- function(X) {
X[toupper(X) != tolower(X)] <- NA
return(as.double(as.character(X)))
}
answered Aug 27, 2015 at 20:12
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.
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
In this article, we are looking towards the way to fix the “(list) object cannot be coerced to type ‘double” error in the R Programming language.
One of the most common errors that a programmer might face in R is:
Error: (list) object cannot be coerced to type 'double'
This error might occur when we try to transform a list of multiple elements into the numeric without using the unlist() function.
When this error might occur:
Let’s create a list first:
Example:
R
myList <- list(10:25, 16:29, 10:12, 25:26, 32)
myList
Output:
Output
Now we will convert the list into its numeric equivalent vector using as.numeric() function. The syntax of this function is given below:
Syntax: as.numeric(vect)
Parameter: vect: a vector of characters
R
myList <- list(10:25, 16:29, 10:12, 25:26, 32)
numeric_vector <- as.numeric(x)
Output:
Output
Since we haven’t used the unlist() function that is why the compiler produced the error: “object that cannot be coerced to type a ‘double’ error message”.
How to Fix the Error:
This error can be fixed by first bundling the list into a vector using unlist() function and then passing it to the numeric() function. The syntax of the unlist() function is given below:
Syntax: unlist(list)
Parameter: list: It represents a list in R
Return Type: Returns a vector
R
myList <- list(10:25, 16:29, 10:12, 25:26, 32)
numeric_vector <- as.numeric(unlist(x))
print(numeric_vector)
Output:
Output
Example:
To verify whether numeric_vector is of type numeric, we can use the class() function. The syntax of the class function is given below:
Syntax: class(x)
Parameter: Here, x represents a R object
Return Type: Returns the type of the passed object i.e, x (vector, list etc)
R
myList <- list(10:25, 16:29, 10:12, 25:26, 32)
numeric_vector <- as.numeric(unlist(x))
class(numeric_vector)
Output:
Output
Also, to verify whether myList and numeric_vector contain an equal number of elements we can use a combination of sum() and lengths() function for myList and length() function for numeric_vector.
The syntax of the sum() function is given below:
Syntax: length(x)
Parameter: Here, x represents a R object like a vector or list
Return Type: Returns the number of elements present in x
R
myList <- list(10:25, 16:29, 10:12, 25:26, 32)
numeric_vector <- as.numeric(unlist(x))
sum(lengths(myList))
length(numeric_vector)
Output:
Output
In this tutorial you’ll learn how to convert a list to a numeric vector in R.
Table of contents:
Here’s how to do it!
Creation of Example Data
As a first step, we have to create some data that we can use in the examples later on:
my_list <- list(1:3, # Example list 5, 10:15) my_list # Print list # [[1]] # [1] 1 2 3 # # [[2]] # [1] 5 # # [[3]] # [1] 10 11 12 13 14 15
The previous RStudio console output shows the structure of our example data: It’s a list containing three numeric list elements.
Example 1: Reproducing Error: (list) object cannot be coerced to type ‘double
This Section illustrates a typical error message, when lists are converted to vectors or arrays. Have a look at the following R code:
as.numeric(my_list) # Wrong R code # Error: (list) object cannot be coerced to type 'double'
As you can see, the RStudio console returns the error message: (list) object cannot be coerced to type ‘double’
The reason is that we cannot simply apply the as.numeric function to a list containing multiple list elements.
Next, I’ll explain how to fix this error. So keep on reading!
Example 2: Appropriate R Code for Conversion of List to Numeric Vector
Example 2 explains how to adequately convert a list to a numeric vector in R. Have a look at the following R code:
as.numeric(unlist(my_list)) # Apply unlist & as.numeric # 1 2 3 5 10 11 12 13 14 15
As you have seen, we used a combination of the unlist and as.numeric functions, i.e. first we are converting our list to a vector and then we convert this vector to numeric. Works smoothly!
Video & Further Resources
Do you need further info on the R programming syntax of this article? Then you might want to have a look at the following video of my YouTube channel. In the video tutorial, I show the examples of this article in RStudio.
Additionally, I can recommend to read the other tutorials of my website.
- The unlist Function in R
- Convert List of Vectors to Data Frame
- Convert Vector to List
- Convert Data Frame Rows to List
- Select First Element of Nested List
- message, warning & stop Functions in R
- The R Programming Language
In this R programming tutorial you learned how to convert lists to arrays. In case you have additional comments and/or questions, don’t hesitate to let me know in the comments section.
The post Error: ‘list’ object cannot be coerced to type ‘double’ appeared first on finnstats.
If you want to read the original article, click here 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.How to Calculate Cross-Correlation in R » finnstats
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.
Decision Tree R Code » Classification & Regression » finnstats
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
Data Visualization Graphs-ggside with ggplot » finnstats
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
To read more visit Error: ‘list’ object cannot be coerced to type ‘double’.
If you are interested to learn more about data science, you can find more articles here finnstats.
The post Error: ‘list’ object cannot be coerced to type ‘double’ appeared first on finnstats.
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
- Solution
- Summary
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:
- How to Solve R Error in lm.fit: na/nan/inf
- How to Solve R Error in apply: dim(X) must have a positive length
- How to Solve R Error in eval(predvars, data, env): object not found
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!
The essence of the problem
This error frequently shows up when you’ve got an list of numeric strings which you want R to treat as numbers. Since these are most assuredly not numbers already, R falters and loudly proclaims: (list) object cannot be coerced to type ‘double’. Thus the error and why you’re here (most likely).
When confronted with a list that contains things which are “not numbers”, in R’s narrow view of the world, the system is throwing this error to ask for some clarity in the matter. Why the fixation on ‘double’ as the target data type ? That’s the default numeric type that R apparently likes. Speaking from practical experience, that particular data type works for most common data sets.
From practical experience, this is less disconcerting that it seems. It is not uncommon for “things” to lurk in large databases, especially databases of international consumer data that were not properly maintained, that do not cast themselves gracefully into numbers if asked to do so. Caution is prudent. This is actually a good thing – we just need to force a little clarity into the act of the conversion.
Fixing This Issue
I recommend politely suggesting to your script that it treat the values in question as numeric. Since verbal approaches are notoriously ineffective, this requires a small correction to your code.
You will want to use the as.numeric function. This will convert the (likely) text values contained within your list into appropriate numeric values.
I should note that the as.numeric() function expects a single element or vector as input, so you may need to adjust your code to apply it properly to each element. Potential ways to use this function:
- Use the unlist() function to convert your list into a single vector and feed the result into as.numeric. It will deliver a list of numeric values for your inspection.
- You can use the lapply function to apply the as.numeric function to each elements of the list
- You can use list sub-setting to target specific elements of the list and feed them into the as.numeric function.
Error: (list) object cannot be coerced to type ‘double’
Содержание
- Error: Coerce List Object to Type Double in R (2 Examples)
- Creation of Example Data
- Example 2: Appropriate R Code for Conversion of List to Numeric Vector
- Video & Further Resources
Error: Coerce List Object to Type Double in R (2 Examples)
In this tutorial you’ll learn how to convert a list to a numeric vector in R.
Table of contents:
Here’s how to do it!
Creation of Example Data
As a first step, we have to create some data that we can use in the examples later on:
my_list Example 1: Reproducing Error: (list) object cannot be coerced to type ‘double
This Section illustrates a typical error message, when lists are converted to vectors or arrays. Have a look at the following R code:
as.numeric(my_list) # Wrong R code # Error: (list) object cannot be coerced to type ‘double’
As you can see, the RStudio console returns the error message: (list) object cannot be coerced to type ‘double’
The reason is that we cannot simply apply the as.numeric function to a list containing multiple list elements.
Next, I’ll explain how to fix this error. So keep on reading!
Example 2: Appropriate R Code for Conversion of List to Numeric Vector
Example 2 explains how to adequately convert a list to a numeric vector in R. Have a look at the following R code:
as.numeric(unlist(my_list)) # Apply unlist & as.numeric # 1 2 3 5 10 11 12 13 14 15
As you have seen, we used a combination of the unlist and as.numeric functions, i.e. first we are converting our list to a vector and then we convert this vector to numeric. Works smoothly!
Video & Further Resources
Do you need further info on the R programming syntax of this article? Then you might want to have a look at the following video of my YouTube channel. In the video tutorial, I show the examples of this article in RStudio.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Accept YouTube Content
Additionally, I can recommend to read the other tutorials of my website.
In this R programming tutorial you learned how to convert lists to arrays. In case you have additional comments and/or questions, don’t hesitate to let me know in the comments section.
Источник
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
This is Akash Mittal, an overall computer scientist. He is in software development from more than 10 years and worked on technologies like ReactJS, React Native, Php, JS, Golang, Java, Android etc. Being a die hard animal lover is the only trait, he is proud of.
Related Tags
- Error,
- R Short
Как исправить: объект (список) нельзя заставить ввести «двойной»
17 авг. 2022 г.
читать 1 мин
Одна распространенная ошибка, с которой вы можете столкнуться в R:
Error: (list) object cannot be coerced to type 'double'
Эта ошибка возникает, когда вы пытаетесь преобразовать список из нескольких элементов в числовой без предварительного использования функции unlist() .
В этом руководстве представлены точные шаги, которые вы можете использовать для устранения этой ошибки.
Как воспроизвести ошибку
Следующий код пытается преобразовать список из нескольких элементов в числовой:
#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'
Поскольку мы не использовали функцию unlist() , мы получили, что объект (список) не может быть принужден к вводу «двойного» сообщения об ошибке.
Как исправить ошибку
Чтобы преобразовать список в числовой, нам нужно убедиться, что мы используем функцию unlist() :
#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
Мы можем использовать функцию class() , чтобы убедиться, что x_num на самом деле является вектором числовых значений:
#verify that x_num is numeric
class(x_num)
[1] "numeric"
Мы также можем проверить, что исходный список и числовой список имеют одинаковое количество элементов:
#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
Мы видим, что две длины совпадают.
Дополнительные ресурсы
В следующих руководствах объясняется, как устранять другие распространенные ошибки в R:
Как исправить в R: имена не совпадают с предыдущими именами
Как исправить в R: контрасты могут применяться только к факторам с 2 или более уровнями
Как исправить в R: более длинная длина объекта не кратна более короткой длине объекта
Написано

Замечательно! Вы успешно подписались.
Добро пожаловать обратно! Вы успешно вошли
Вы успешно подписались на кодкамп.
Срок действия вашей ссылки истек.
Ура! Проверьте свою электронную почту на наличие волшебной ссылки для входа.
Успех! Ваша платежная информация обновлена.
Ваша платежная информация не была обновлена.





