2

I am trying to write 2 functions in R, one that creates a matrix and defines mutator and accessor functions (I think that's the right terms) for that matrix and its inverse, and another that operates on the type of objects defined in the first function to compute their inverses (assume my matrix is invertable).

The second function 1st checks if the variable inv has something in it, if it doesn't then it is to compute that matrix's inverse, and if there is something in inv, the second function is to retrieve that value and print it. I want to be able to implement it so my input and output look like this:

>matrix<-makeMatrix(1:4,2,2)
>calcAndStoreInv(matrix)
    [,1] [,2]
[1,] -2   1.5
[2,] 1   -0.5
>calcAndStoreInv(matrix)
getting cached data
   [,1] [,2]
[1,] -2   1.5
[2,] 1   -0.5

Here's my code

makeMatrix<-function(x=matrix()){
    inv<-NULL
    set<-function(y){
        x<<-y
        inv<<-NULL
        }
    get<-function() x
    setInv<-function(input_inverse) inv<<-inpuut_inverse
    getInv<-function () inv
    list(set=set, get=get, setInv=setInv, getInv=getInv)

CalcAndStoreInv<-function(x,...){
    inv<-x$getinv()
    if (!is.null(inv)){
        print("Getting cached data")
        return(inv)
    }
    data<-x$get
    inv<-solve(data)
    x$setInv(inv)
}

When I run through my code line by line on RStudio, it behaves the way I expect it. However when I run it all at once I get an "Error in as.vector(x, mode_) ; cannot coerce type 'closure' to vector type of 'any'. My understanding of closure is pretty limited- from what I read I think closure is an association between a function and it's environment, including local variables defined in the function. I read that as a property, and not a type of vector.

So, in the context of R, what exactly is closure? How does it apply to my code? Am I reading the error message correctly in thinking closure is a type of vector (which would make it a data type right) or is there something else I'm missing?

user3299824
  • 43
  • 1
  • 4
  • There appear to be at least a few issues in the reproducibility of your code. First off, looks like you are missing a `}` for the `makeMatrix` function. Next, your call to `makeMatrix` has too many arguments. – jmuhlenkamp Dec 09 '17 at 07:01
  • What do you mean by makeMatrix has too many arguments? Isn't the only argument x=matrix()? I was able to resolve the issue by fixing the missing bracket, correct the line inv – user3299824 Dec 10 '17 at 00:17

0 Answers0