I am working on am R assignment of lexical looping and I am a newbie to R. I have two methods, my code is below. I have just given line numbers to make it easier for me to explain and for you to understand, they doesn't exist in real and anyway this method is not the problem as I believe.
makeCacheMatrix <- function(x = matrix()) {
inv<- NULL
set<-function(y){
inv<<- NULL
x<<-y
}
get<-function() x
getinverse<-function() inv
setinverse<-function(inversed_matrix) inv<-inversed_matrix
list(setmatrix=set, getmatrix=get, getinverse = getinverse, setinverse = setinverse)
}
This function works well and all the data gets populated as expected, I have tested it explicitly. Now I create an object from this function
my_matrix<-makeCacheMatrix(iris_subset)
Now the second function
cacheSolve <- function(cachedMatrix, ...) {
inversed_matrix<-cachedMatrix$getinverse
if(!is.null(inversed_matrix)){
message("Getting cached inversed matrix")
return(inversed_matrix)
}
inversed_matrix<-cachedMatrix$getmatrix
cachedMatrix$setinverse(inversed_matrix)
inversed_matrix
}
Now I execute following line of code, where "my_matrix" is the object of the function makeCacheMatrix i created above
m<-cacheSolve(my_matrix)
This is where I have problem. When I perform the null check at Line 3 it fails because it instead of returning the value, the code in Line 2 returns the actual code from the function "makeCacheMatrix". i.e instead of a NULL on the first run it returns the text "function() inv", which is actually the code written in the function makeCacheMatrix
Here's the data:
structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6), Sepal.Width = c(3.5,
3, 3.2, 3.1), Petal.Length = c(1.4, 1.4, 1.3, 1.5), Petal.Width = c(0.2,
0.2, 0.2, 0.2)), .Names = c("Sepal.Length", "Sepal.Width", "Petal.Length",
"Petal.Width"), row.names = c(NA, 4L), class = "data.frame")