简体   繁体   中英

R error, $ operator is invalid for atomic vectors

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
}

I tried running this code in R and i got the error $ operator is invalid for atomic vectors, which is quite understandable since x there is not recursive. but as evident from the code i need to work on a cached value. As far as i know the first function is working fine. Is there any other way I can get the cached values from first function, a replacement for $ operator? Attached is a screenshot of the output of first function and the error in second function

output:

 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

In your instruction you pass x as atomic vector. That is why $ does not work. Use it like this: cachemean(makeVector(1:6)) and you get a result.

It won't be cached, though, because this code creates a temporary variable that will get lost. You need a place to store it to. Look at this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM