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 }
vec <- makeVector(c(1, 2, 3, 4)) cachemean(vec) # Calculates and caches the mean cachemean(vec) # Retrieves the cached mean
makeCacheMatrix <- function(x = matrix()) { j <- NULL set <- function(y){ x <<- y j <<- NULL } get <- function()x setInverse <- function(inverse) j <<- inverse getInverse <- function() j list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } The first call computes and caches the mean, while the second call retrieves it from the cache