首页 > 解决方案 > 使用列表获取原子错误

问题描述

我在 R 中实现了一个 A-star 算法,并在尝试使用 sapply 函数时不断收到“包装期间的错误:$ 运算符对原子向量无效”。

这是我的结构:


frontier <- list()
starting_node = list(1, 1)
frontier <- append(frontier, list(node = starting_node, cost = 0, path = list()))
costs = sapply(frontier,function(item)item$cost)

这将返回错误。有谁知道是什么导致了这个问题?我觉得好像我正在使用列表,$ 操作应该没问题?

标签: r

解决方案


您的列表边界的成本元素实际上是未定义 $ 运算符的原子类型数字:

library(tidyverse)
frontier <- list()
starting_node = list(1, 1)
frontier <- append(frontier, list(node = starting_node, cost = 0, path = list()))
frontier %>% sapply(class)
#>      node      cost      path 
#>    "list" "numeric"    "list"

reprex 包于 2021-09-09 创建(v2.0.1)

sapply使用 $ 将函数应用于每个元素,因此每个元素本身必须是一个列表。


推荐阅读