简体   繁体   English

R 编程:矩阵的值在哪里得分?

[英]R Programming: Where is the value of the matrix scored?

I have a function which returns a list of 3 sub functions as follows:我有一个 function 它返回 3 个子函数的列表,如下所示:

makeCacheMatrix <- function(x = matrix()) {
inversedMatrix <- NULL
get <- function() x
setMatrix <- function(matrix) inversedMatrix <<- matrix
getMatrix <- function() inversedMatrix
list(get = get,
   setMatrix = setMatrix,
   getMatrix = getMatrix)
}

When I create an object by passing the matrix(1:4, 2, 2) to this function using matrixcal <- makeCacheMatrix(matrix(1:4, 2, 2)) the value of the matrix(1:4, 2, 2) gets stored somewhere.当我通过使用matrixcal <- makeCacheMatrix(matrix(1:4, 2, 2))matrix(1:4, 2, 2)传递给这个 function 创建一个 object 时, matrix(1:4, 2, 2)存储在某处。 I want to understand where this value is being stored as I do not see it in R studio in the Global environment.我想了解这个值的存储位置,因为我在全球环境的 R 工作室中看不到它。 Clearly it is being stored somewhere as I can access it later using matrixcal$get()显然它被存储在某个地方,因为我以后可以使用matrixcal$get()访问它

Thanks in advance!提前致谢!

If you call your function如果你打电话给你的 function

foo <- makeCacheMatrix(matrix(1:4, 2, 2))

Then look at the object然后看object

foo
# $get
# function() x
# <environment: 0x0000021849b5da78>

# $setMatrix
# function(matrix) inversedMatrix <<- matrix
# <environment: 0x0000021849b5da78>

# $getMatrix
# function() inversedMatrix
# <environment: 0x0000021849b5da78>

You'll see that each of the functions has an associated environment (your exact numbers/digits will be different each time you run the function).您会看到每个函数都有一个关联的环境(每次运行该函数时,您的确切数字/数字都会不同)。 Your function has created a closure environment to store the variables and functions created.您的 function 已经创建了一个闭包环境来存储创建的变量和函数。

You can access that environment via您可以通过以下方式访问该环境

environment(foo$get)

which just gives you the environment object.这只是为您提供了 object 环境。 You can list the contents of that environment with您可以列出该环境的内容

ls.str(environment(foo$get))
# get : function ()  
# getMatrix : function ()  
# inversedMatrix :  NULL
# setMatrix : function (matrix)  
# x :  int [1:2, 1:2] 1 2 3 4

And there you'll see the original matrix stored in the x value of that environment.在那里你会看到存储在那个环境的x值中的原始矩阵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM