本文介绍了在 R 中缓存向量的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 R 并在练习作业中遇到了一些代码.

I am learning R and came across some code as part of the practice assignment.

 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)
 }

文档说:

函数,makeVector 创建一个特殊的向量",它是真正包含一个函数的列表

The function, makeVector creates a special "vector", which isreally a list containing a function to

  1. 设置向量的值
  2. 获取向量的值
  3. 设置平均值
  4. 获取平均值

但我无法理解该函数是如何工作的,除了它在特定环境中为变量 m 分配平均值.

But i can not understand how the function works except for the point that it is assigning mean value to the variable m in that particular environment.

推荐答案

m 首先将均值设置为 NULL 作为未来值的占位符

m <- NULL begins by setting the mean to NULL as a placeholder for a future value

set 定义了一个函数来将向量 x 设置为一个新的向量 y,并将平均值 m 重置为 NULL

set <- function(y) {x <<- y; m <<- NULL} defines a function to set the vector, x, to a new vector, y, and resets the mean, m, to NULL

get <- function() x 返回向量,x

setmean <- function(mean) m <<- mean 将均值 m 设置为 mean

getmean 返回平均值,m

list(set = set, get = get,setmean = setmean,getmean = getmean) 返回 'specialvector' 包含刚刚定义的所有函数

list(set = set, get = get,setmean = setmean,getmean = getmean) returns the 'specialvector' containing all of the functions just defined

这篇关于在 R 中缓存向量的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 21:09