**Read this better directly on GITHUB**

This is the second post of the series ” R Programming”. Here it is possible to find the summary of the tasks that I performed when I took this course at Coursera.

**Assignment 2:**

This second programming assignment will require you to write an R function that is able to cache potentially time-consuming computations. For example, taking the mean of a numeric vector is typically a fast operation. However, for a very long vector, it may take too long to compute the mean, especially if it has to be computed repeatedly (e.g. in a loop). If the contents of a vector are not changing, it may make sense to cache the value of the mean so that when we need it again, it can be looked up in the cache rather than recomputed. In this Programming Assignment you will take advantage of the scoping rules of the R language and how they can be manipulated to preserve state inside of an R object.

### Example: Caching the Mean of a Vector

In this example we introduce the `<<-`

operator which can be used to assign a value to an object in an environment that is different from the current environment. Below are two functions that are used to create a special object that stores a numeric vector and caches its mean.

The first function, `makeVector`

creates a special “vector”, which is 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

12345678910111213makeVector <- function(x = numeric()) {m <- NULLset <- function(y) {x <<- ym <<- NULL}get <- function() xsetmean <- function(mean) m <<- meangetmean <- function() mlist(set = set, get = get,setmean = setmean,getmean = getmean)}

The following function calculates the mean of the special “vector” created with the above function. However, it first checks to see if the mean has already been calculated. If so, it`get`

s the mean from the cache and skips the computation. Otherwise, it calculates the mean of the data and sets the value of the mean in the cache via the`setmean`

function.

1234567891011cachemean <- 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}

Assignment: Caching the Inverse of a Matrix

Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of a matrix rather than computing it repeatedly (there are also alternatives to matrix inversion that we will not discuss here). Your assignment is to write a pair of functions that cache the inverse of a matrix.

Write the following functions:

`makeCacheMatrix`

: This function creates a special “matrix” object that can cache its inverse.`cacheSolve`

: This function computes the inverse of the special “matrix” returned by`makeCacheMatrix`

above. If the inverse has already been calculated (and the matrix has not changed), then`cacheSolve`

should retrieve the inverse from the cache.

Computing the inverse of a square matrix can be done with the `solve`

function in R. For example, if `X`

is a square invertible matrix, then `solve(X)`

returns its inverse.

For this assignment, assume that the matrix supplied is always invertible.

In order to complete this assignment, you must do the following:

- Fork the GitHub repository containing the stub R files at https://github.com/rdpeng/ProgrammingAssignment2 to create a copy under your own account.
- Clone your forked GitHub repository to your computer so that you can edit the files locally on your own machine.
- Edit the R file contained in the git repository and place your solution in that file (please do not rename the file).
- Commit your completed R file into YOUR git repository and push your git branch to the GitHub repository under your account.
- Submit to Coursera the URL to your GitHub repository that contains the completed R code for the assignment.

### Solution:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
## Functions to test the concept of Lexical Scopping ## We create an object "makeacheMatrix" which has ## functions which access to a variable in another scope: the cached result. ## A) Initialize the Object, wrapper, for the Matrix "x". This object/wrapper will contain ## the data of the matrix, the cached result of his inverse (if any) and functions to access ## and modify the cached result, at the same time than the Matrix. makeCacheMatrix <- function(x = matrix()) { #vble where to store the cached result: cachedInverse <- NULL #function, reset the matrix (x) content to the matrix sent in the argument (y) set <- function(y) { x <<- y cachedInverse <<- NULL } #function, return the content of the matrix (x) get <- function() x #function, call once inverse is calculated so it will be cached as inverse of the matrix (x) setInverse <- function(inverse) cachedInverse <<- inverse #function, return the inverse cached getInverse <- function() cachedInverse list(set = set, get = get, setInverse = setInverse, getInverse = getInverse) } ## B) Function that will get as a parameter the object/wrapper including the matrix to calcualte the ## inverse from, his cached inverse and functions to set or get these variables. ## This function which check if the inverse has been calculated previously, extracting it from ## the cache, otherwise, the inverse will be calculated and stored in the wrapper/cache for future usage. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' #extract the cached inverse for the "x" matrix from his wrapper inv <- x$getInverse() #if it was calculated previously, return the cached inverse, otherwise ... continue if(!is.null(inv)) { message("getting cached data") return(inv) } #get the content of the Matrix from his wrapper object in "data" data <- x$get() #calculate the inverse of the Matrix inv <- solve(data, ...) #store the inverse in the wrapper object for of the Matrix x$setInverse(inv) inv } # C) How to use these functions for testing the lexical scoping?? # c.1) Create an object which will store the contenct of the matrix, his inverse, and functions to access them # > wrapper= makeCacheMatrix(); # # c.2) Assign the content of the matrix to calculate the inverse to this wrapper # > wrapper$set(matrix(1:4,2,2)) # # c.3) The object contains the matrix. Call the function above "cacheSolve" which will check if # the invese has been calculated and cached previously. Otherwhise will perform these operations. # # Calculate the inverse (1st time) of the matrix included into the wrapper object #> cacheSolve(wrapper) # [,1] [,2] # [1,] -2 1.5 # [2,] 1 -0.5 # # The second time it will retrieve it from cache # > cacheSolve(wrapper) # getting cached data # [,1] [,2] # [1,] -2 1.5 # [2,] 1 -0.5 # |

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
C) How to use these functions for testing the lexical scoping?? c.1) Create an object which will store the contenct of the matrix, his inverse, and functions to access them > wrapper= makeCacheMatrix(); c.2) Assign the content of the matrix to calculate the inverse to this wrapper > wrapper$set(matrix(1:4,2,2)) c.3) The object contains the matrix. Call the function above "cacheSolve" which will check if the invese has been calculated and cached previously. Otherwhise will perform these operations. Calculate the inverse (1st time) of the matrix included into the wrapper object > cacheSolve(wrapper) [,1] [,2] [1,] -2 1.5 [2,] 1 -0.5 The second time it will retrieve it from cache > cacheSolve(wrapper) getting cached data [,1] [,2] [1,] -2 1.5 [2,] 1 -0.5 |