khan - 5 months ago 83

R Question

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`

really a list containing a function to

- set the value of the vector
- get the value of the vector
- set the value of the mean
- 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

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