【问题标题】:R error, $ operator is invalid for atomic vectorsR 错误,$ 运算符对原子向量无效
【发布时间】:2020-05-23 11:34:42
【问题描述】:
makeVector <- function(x = numeric()) {
        m <- NULL
        set <- function(y) {
                x <<- y
                m <<- NULL
        }
        get <- function() x
        setmean <- function(mean) m <<- mean
        getmean <- function() m
        list(set = set, get = get,
             setmean = setmean,
             getmean = getmean)
}

cachemean <- function(x, ...) {
        m <- x$getmean()
        if(!is.null(m)) {
                message("getting cached data")
                return(m)
        }
        data <- x$get()
        m <- mean(data, ...)
        x$setmean(m)
        m
}

我尝试在 R 中运行此代码,但得到错误 $ operator is invalid for atomic vectors,这是可以理解的,因为 x 没有递归。 但从代码中可以明显看出,我需要处理缓存值。 据我所知,第一个功能工作正常。 有没有其他方法可以从第一个函数中获取缓存值,替代 $ 运算符? Attached is a screenshot of the output of first function and the error in second function

输出:

 makeVector(c(2,4,6,8))
$set
function(y) {
    x <<- y
    m <<- NULL
  }
<environment: 0x0000019d4335e130>

$get
function() x
<environment: 0x0000019d4335e130>

$setmean
function(mean) m <<- mean
<environment: 0x0000019d4335e130>

$getmean
function() m
<environment: 0x0000019d4335e130>

> cachemean(c(2,4,6,8))
Error in x$getmean : $ operator is invalid for atomic vectors

【问题讨论】:

  • 能否也提一下输出,以便用户可以通过搜索复制、引用和找到它
  • 当然,我编辑问题。

标签: r


【解决方案1】:

在您的指令中,您将 x 作为原子向量传递。这就是为什么 $ 不起作用。像这样使用它:cachemean(makeVector(1:6)) 你会得到一个结果。

但它不会被缓存,因为此代码会创建一个会丢失的临时变量。你需要一个地方来存放它。看看这个:

test <- makeVector(c(2,4,6,8))
test$getmean()
# returns NULL because R discards the object when the function has finished
cachemean(test)
test$getmean()
# returns 5

【讨论】:

  • 好的,成功了。该功能现在运行没有错误。但它没有缓存值。它返回平均值作为计算的新值(没有打印语句“获取缓存值”)。这是为什么呢?
  • 您存放它的地方会丢失。我更新了我的答案。
猜你喜欢
  • 2018-08-23
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 2021-08-20
  • 2020-06-21
  • 2021-11-07
  • 1970-01-01
相关资源
最近更新 更多