我试图在计算R中矩阵的逆数时使用环境缓存,如下所示(从该网址https://github.com/mehulpatel21/Data-Science-Specialization-JHU/blob/master/2)%20R%20Programming/cachematrix.R获得的代码:
makeCacheMatrix <- function(x = matrix()) {
## Initialize the inverse property
i <- NULL
## Method to set the matrix
set <- function( matrix ) {
m <<- matrix
i <<- NULL
}
## Method the get the matrix
get <- function() {
## Return the matrix
m
}
## Method to set the inverse of the matrix
setInverse <- function(inverse) {
i <<- inverse
}
## Method to get the inverse of the matrix
getInverse <- function() {
## Return the inverse property
i
}
## Return a list of the methods
list(set = set, get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## Compute the inverse of a special matrix returned by "makeCacheMatrix"
## above. If the inverse is already calculated (and the matrix has not
## changed), then the "cachesolve" should retrieve the inverse from the cache.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
m <- x$getInverse()
## Just return the inverse if its already set
if( !is.null(m) ) {
message("getting cached data")
return(m)
}
## Get the matrix from our object
data <- x$get()
## Calculate the inverse using matrix multiplication
m <- solve(data) %*% data
## Set the inverse to the object
x$setInverse(m)
## Return the matrix
m
}
为了测试代码,我定义了如下矩阵:
d = matrix(1:1000000, 5000, 200)
d = as.data.frame(d)
cacheSolve(d)
上面的代码给我以下错误:
Error in x$getInverse() : attempt to apply non-function
我的测试方式不正确吗?
答案 0 :(得分:1)
将d = as.data.frame(d)
传递给函数cacheSolve(d)
会产生错误
然后调用m <- x$getInverse()
并产生错误,因为x作为未定义getInverse()函数的data.frame传入。
以下修复程序通过首先创建您定义的makeCacheMatrix()并通过$set()
调用设置其值,并将其传递给data.frame d
d = matrix(1:1000000, 5000, 200)
d = as.data.frame(d)
cm = makeCacheMatrix(d)
cm$set(d)
cacheSolve(cm)