R 记录sample函数返回的返回值

R 记录sample函数返回的返回值,r,sample,R,Sample,我需要创建一个throw函数,每当用户使用throw()函数时,该函数返回一个介于1到6之间的随机数。但是我需要在用户不知道的变量中记录用户得到的值。我的想法是,我可以在以后的某个时间点交叉验证报告的值和实际值 我是这样做的 throw<-function(){ dice<-c(1:6) A<-c(0,0) x<-sample(dice,1) fetches<-c(A,x) x } throw我会使用

我需要创建一个throw函数,每当用户使用throw()函数时,该函数返回一个介于1到6之间的随机数。但是我需要在用户不知道的变量中记录用户得到的值。我的想法是,我可以在以后的某个时间点交叉验证报告的值和实际值

我是这样做的

throw<-function(){
   dice<-c(1:6)
    A<-c(0,0)
       x<-sample(dice,1)
        fetches<-c(A,x)
          x
}
throw我会使用一个“不可见”的环境并预先分配一组值:

#objects with a name starting with . are invisible
.e <- new.env(, parent = .GlobalEnv)
#pre-allocate
.e$fetches <- integer(100)

throw<-function(){ 
  dice <- c(1:6)
  x <- sample(dice,1)
  #check if vector has room for new values, grow if necessary
  if (sum(.e$fetches == 0L) == 0L) .e$fetches <- c(.e$fetches, integer(100))
  .e$fetches[which.min(.e$fetches)] <- x
  return("complete")
}

set.seed(42)
throw()
#[1] "complete"
throw()
#[1] "complete"
.e$fetches[.e$fetches != 0L]
#[1] 6 6
#名称以开头的对象。看不见

非常感谢。我计划将其与一个闪亮的应用程序集成。有一个看不见的环境会影响到这一点吗?我对闪亮没有经验。我不认为会有问题,但我真的不知道。