【发布时间】: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