R programming: cache the inverse of a matrix
I don't know your exact assignment, but I would change your function slightly:
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setInverse <- function() inv <<- solve(x) #calculate the inverse
getInverse <- function() inv
list(set = set,
get = get,
setInverse = setInverse,
getInverse = getInverse)
}
You can then use it like this:
funs <- makeCacheMatrix()
funs$set(matrix(1:4, 2))
funs$get()
# [,1] [,2]
#[1,] 1 3
#[2,] 2 4
funs$setInverse()
funs$getInverse()
# [,1] [,2]
#[1,] -2 1.5
#[2,] 1 -0.5
The exercise is probably intended to teach you closures. The point is that x
and inv
are stored in the enclosing environment of the set
, get
, setInverse
, getInverse
functions. That means the environment within which they were defined, i.e., the environment created by the makeCacheMatrix()
call. See this:
ls(environment(funs$set))
#[1] "get" "getInverse" "inv" "set" "setInverse" "x"
As you see not only are the four functions in this environment, but also the x
and inv
objects (a consequence of using <<-
). And the get
and getInverse
functions only fetch these from their enclosing environment.
Caching the Inverse of a Matrix
Given the code in the OP, x$getinverse()
should return NULL
because one must execute cacheSolve()
in order to populate the cache. I explain the details of how the sample code for this assignment works, including the need for the second function to populate the cache, in the stackoverflow answer Caching the Mean of a Vector.
That said, the program has three defects that prevent it from operating correctly.
- In
cacheSolve()
,m<-x$getinverse
sets the value ofm
to a function, not the result of executing thegetinverse()
function - In
cacheSolve()
,data<-x$get
returns the address of the functionget()
instead of its contents. - In
cacheSolve()
,x$setinverse(m)
fails because the functionsetinverse()
inmakeCacheMatrix
does not include an input argument.
Note that since I am a Community Mentor for the Hopkins R Programming course, I'm not allowed to post a complete solution because it would violate the Coursera Honor Code.
Once the errors are corrected, the code works like this:
> x <-makeCacheMatrix(matrix(c(1,0,0,0,1,0,0,0,2),ncol=3,nrow=3))
> cacheSolve(x)
[,1] [,2] [,3]
[1,] 1 0 0.0
[2,] 0 1 0.0
[3,] 0 0 0.5
> x$get()
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 2
> x$getinverse()
[,1] [,2] [,3]
[1,] 1 0 0.0
[2,] 0 1 0.0
[3,] 0 0 0.5
>
Returning the inverse matrix from a cached object in R
Error in as.vector(x, mode) : cannot coerce type 'closure' to vector of type 'any'
Means that you try to coerce a function to a vector/matrix. Indeed in this line:
matrix <- x$get
m <- solve(matrix, ...)
matrix
is a function , or solve
need a matrix.
You just need to change this line :
matrix <- x$get
by
matrix <- x$get()
On coursera R-programming course Assignment 2 Lexical Scoping
x <<- y
creates x
, which is then retrieved by get()
. Note that get
is also a base function and is being overwritten here. I would advocate in avoiding this, even though it's confined to a function. An ad hoc solution would be to reach base get
function through base::get
.
Line get <- function() x
is a "short" version of
get <- function() {
x
}
Short version will work if you have only one line or separate statements using ;
. The biggest beef I have with this piece of code is no use of argument. This may be fine with Java or some other language, but I don't consider that an R way. Modifying objects like this can lead to unintended behavior which could lead to painstaking debugging.
setInverse
and getInverse
are not the same. What they do is set inverse or get it.
Caching the mean of a Vector in R
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
Related Topics
Specify Height and Width of Ggplot Graph in Rmarkdown Knitr Output
Ggplot2: Splitting Facet/Strip Text into Two Lines
Convert Hours:Minutes:Seconds to Minutes
Finding Non-Numeric Data in a Data Frame or Vector
Increase Space Between Bars in Ggplot
Merge Overlapping Ranges into Unique Groups, in Dataframe
In R Plotly Subplot Graph, How to Show Only One Legend
Rcpp Function to Select (And to Return) a Sub-Dataframe
How to Read Specific Rows of CSV File with Fread Function
Extract Digit from Numeric in R
Select Rows of a Data.Frame That Contain Only Numbers in a Certain Column
Return Pmin or Pmax of Data.Frame with Multiple Columns
How to Calculate the Mean of Those Columns in a Data Frame with the Same Column Name
Color Points with the Color as a Column in Ggplot2
How to Find Difference Between Values in Two Rows in an R Dataframe Using Dplyr