Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the inverse matrix from a cached object in R

Tags:

r

matrix

Disclosure: This is from a programming assignment from a Coursera Course called R programming

The assignment is regarding lexical scoping and caching functions that may require a long computation time. Specifically I am using solve() to find the inverse of a matrix and cache it using a free floating variable. I am returning an error as described below.

First I stored a function in a variable a<-makeCacheMatrix()Then I run a$set(matrix(1:4,2,2)to store a matrix

When I run cacheSolve(a) I get Error in as.vector(x, mode) : cannot coerce type 'closure' to vector of type 'any'

From my understanding I suspect that I might be passing an atomic vector when it requires a matrix but I am not sure how to fix

My code:

makeCacheMatrix <- function(x = matrix()) {
  m<-NULL
  set<-function(y){
  x<<-y
  m<<-NULL
}
get<-function() x
setmatrix<-function(solve) m<<- solve
getmatrix<-function() m
list(set=set, get=get,
   setmatrix=setmatrix,
   getmatrix=getmatrix)
}

cacheSolve <- function(x=matrix(), ...) {
    m<-x$getmatrix()
    if(!is.null(m)){
      message("getting cached data")
      return(m)
    }
    matrix<-x$get
    m<-solve(matrix, ...)
    x$setmatrix(m)
    m
}
like image 365
Michael Queue Avatar asked May 22 '14 01:05

Michael Queue


1 Answers

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() 
like image 181
agstudy Avatar answered Oct 25 '22 07:10

agstudy