R语言如何修复:list object cannot be coerced to type double

R语言如何修复:list object cannot be coerced to type double

在这篇文章中,我们将探讨如何在R编程语言中修复”(list)对象不能被胁迫为’double’类型 “的错误。

在R语言中,程序员可能面临的最常见的错误之一是。

Error: 
(list) object cannot be coerced to type 'double'
Bash

当我们试图将一个多元素的列表转化为数字而不使用unlist()函数时,可能会发生这个错误。

当这个错误可能发生时

让我们先创建一个列表。

例子

# Make a list
myList <- list(10:25, 16:29, 10:12, 25:26, 32)
 
# Print the list
myList
Bash

输出

R语言如何修复:list object cannot be coerced to type double

输出

现在我们将使用as.numeric()函数将列表转换为其数字等价矢量。这个函数的语法如下。

语法: as.numeric(vect)

参数: vect:一个字符向量

# Make a list
myList <- list(10:25, 16:29, 10:12, 25:26, 32)
 
# Convert list to numeric vector
numeric_vector <- as.numeric(x)
Bash

输出

R语言如何修复:list object cannot be coerced to type double

输出

由于我们没有使用unlist()函数,这就是为什么编译器产生了错误。”无法强制输入’double’的对象的错误信息”。

如何修复这个错误

这个错误可以通过首先使用unlist()函数将列表捆绑成一个向量,然后将其传递给numeric()函数来解决。unlist()函数的语法如下。

语法: unlist(list)

参数: list。它代表R中的一个列表

返回类型: 返回一个向量

# Make a list
myList <- list(10:25, 16:29, 10:12, 25:26, 32)
 
# Convert list to numeric
numeric_vector <- as.numeric(unlist(x))
 
# Print the numeric equivalent
print(numeric_vector)
Bash

输出

R语言如何修复:list object cannot be coerced to type double

输出

例子

为了验证 numeric_vector 是否属于 numeric 类型,我们可以使用 class() 函数。class函数的语法如下。

语法: class(x)

参数: 这里,x代表一个R对象

返回类型: 返回传递对象的类型,即x(向量、列表等)。

# Make a list
myList <- list(10:25, 16:29, 10:12, 25:26, 32)
 
# Convert list to numeric
numeric_vector <- as.numeric(unlist(x))
 
# Print the numeric equivalent
class(numeric_vector)
Bash

输出

R语言如何修复:list object cannot be coerced to type double

输出

另外,为了验证myList和numeric_vector是否包含相同数量的元素,我们可以对myList使用sum()和lengths()函数,对numeric_vector使用length()函数的组合。

sum()函数的语法如下。

语法: length(x)

参数: 这里,x代表一个R对象,如矢量或列表。

返回类型: 返回x中存在的元素的数量

# Make a list
myList <- list(10:25, 16:29, 10:12, 25:26, 32)
 
# Convert list to numeric
numeric_vector <- as.numeric(unlist(x))
 
# Print the total number of
# elements in the list
sum(lengths(myList))
 
# Print the total number of
# elements in the vector
length(numeric_vector)
Bash

输出

R语言如何修复:list object cannot be coerced to type double

输出

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册