khan khan - 3 months ago 52
R Question

Caching the mean of a Vector in R

I am learning R and came across some code as part of the practice assignment.

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)
}


The documentation says:

The function,
makeVector
creates a special "vector", which is
really a list containing a function to


  1. set the value of the vector

  2. get the value of the vector

  3. set the value of the mean

  4. get the value of the mean



But i can not understand how the function works except for the point that it is assigning mean value to the variable m in that particular environment.

Answer

m <- NULL begins by setting the mean to NULL as a placeholder for a future value

set <- function(y) {x <<- y; m <<- NULL} defines a function to set the vector, x, to a new vector, y, and resets the mean, m, to NULL

get <- function() x returns the vector, x

setmean <- function(mean) m <<- mean sets the mean, m, to mean

getmean <- function() m returns the mean, m

list(set = set, get = get,setmean = setmean,getmean = getmean) returns the 'special vector' containing all of the functions just defined