在R中缓存Vector的平均值(列表) [英] Caching the mean of a Vector in R (list)
本文介绍了在R中缓存Vector的平均值(列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
This is a follow up to Caching the mean of a Vector in R and is specifically about the last line of code
list(set = set, get = get, setmean = setmean, getmean = getmean)
我不了解list
在做什么.在链接的问题上给出的答案:
I am not understanding what the list
is doing. The answer given at the linked question:
list()返回包含所有已定义函数的特殊向量"
list() returns the 'special vector' containing all of the functions just defined
对我来说没有多大意义.我认为makeVector
应该返回一个具有适当的set
和get
方法的对象,但是现在确定此list()
的工作方式.左侧的set
是什么,右侧的set
是什么?
does not make much sense to me. I think that makeVector
should be returning an object which has the approriate set
and get
methods, but now sure how this list()
is doing that. What is the set
on the left-hand side and what is the set
on the right-hand side?
makeVector <- function(x = numeric()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setmean <- function(mean) m <<- mean
getmean <- function() m
list(set = set, get = get,
setmean = setmean,
getmean = getmean)
}
推荐答案
> z<- makeVector()
> z
上面的语句将返回"makeVector"函数中所有四个函数的列表,即$ set,$ get,$ setmean,$ getmean
$set
function (y)
{
x <<- y
m <<- NULL
}
<environment: 0x0000000008935dc8>
$get
function ()
x
<environment: 0x0000000008935dc8>
$setmean
function (mean)
m <<- mean
<environment: 0x0000000008935dc8>
$getmean
function ()
m
<environment: 0x0000000008935dc8>
现在您可以将每个函数作为列表对象进行访问,如下所示:
> z$set(c(1:20))
> z$get()
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
> z$setmean(mean(z$get()))
> z$getmean()
[1] 10.5
这篇关于在R中缓存Vector的平均值(列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文