Lexical Scoping in R

r

#1

I recently came through this concept of Lexical Scoping in R via the below two functions:
1.makeVector:
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)
}
This function is a special function used to 1) Set & get the value of the vector 2)Set & get the value of the mean of the vector.

2.cachemean:
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
}
This function calculates the mean of the vector.However it first finds out if the mean has already been calculated,in which case it returns the cached value of the mean.
I am not being able to understand the flow completely.
Any help is appreciated.!!
Note:It is a part of the R programming course in Coursera.


#2

you should try running it part by part to understand it

if(!is.null(m))

! indicates logical negation (NOT).

is.null returns TRUE if its argument is NULL and FALSE otherwise.

one way to help you- try ?fun for anything called “fun” you dont understand- it gives you help

and try running it line by line

R is a vast vast language and even I use a lot of help