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
}
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With