1

这是我从“奇怪”问题循环中提出的下一个问题。

我在 R 控制台和 RStudio 中发现了相同的代码执行差异,但无法理解其原因。它还与 RStudio 和 R.NET 中“track”包的不正确工作有关,正如我之前在R.NET 中不正确的 track package 工作中所写的那样

那么,让我们看一下来自https://search.r-project.org/library/base/html/taskCallback.html的示例

(为了正确输出 RStudio 中的 sum 数据,我对其进行了一些修正)

times <- function(total = 3, str = "Task a") {
   ctr <- 0

   function(expr, value, ok, visible) {
    ctr <<- ctr + 1
    cat(str, ctr, "\n")
    if(ctr == total) {
      cat("handler removing itself\n")
    }
    return(ctr < total)
   }
 }

 # add the callback that will work for
 # 4 top-level tasks and then remove itself.
 n <- addTaskCallback(times(4))

 # now remove it, assuming it is still first in the list.
 removeTaskCallback(n)

## Not run: 
# There is no point in running this
# as
 addTaskCallback(times(4))

 print(sum(1:10))
 print(sum(1:10))
 print(sum(1:10))
 print(sum(1:10))
 print(sum(1:10))

## End(Not run)

R控制台中的输出:

> 
>  # add the callback that will work for
>  # 4 top-level tasks and then remove itself.
>  n <- addTaskCallback(times(4))
Task a 1 
> 
>  # now remove it, assuming it is still first in the list.
>  removeTaskCallback(n)
[1] TRUE
> 
> ## Not run: 
> # There is no point in running this
> # as
>  addTaskCallback(times(4))
1 
1 
Task a 1 
> 
>  print(sum(1:10))
[1] 55
Task a 2 
>  print(sum(1:10))
[1] 55
Task a 3 
>  print(sum(1:10)) 
[1] 55
Task a 4 
handler removing itself
>  print(sum(1:10))
[1] 55
>  print(sum(1:10))
[1] 55
> 
> ## End(Not run)
> 

好的,让我们在 RStudio 中运行它。输出:

> source('~/callbackTst.R')
[1] 55
[1] 55
[1] 55
[1] 55
[1] 55
Task a 1 
> 

第二次运行给我们这个:

> source('~/callbackTst.R')
[1] 55
[1] 55
[1] 55
[1] 55
[1] 55
Task a 2 
Task a 1 
> 

第三:

> source('~/callbackTst.R')
[1] 55
[1] 55
[1] 55
[1] 55
[1] 55
Task a 3 
Task a 2 
Task a 1 
> 

等等。

RStudio 和 R 控制台之间有一个奇怪的区别,我不知道为什么。有人可以帮我吗?是虫子还是正常,我有弯曲的手?

谢谢你。

PS这篇文章与“track”包的正确工作有关,因为“track.start”方法包含这部分代码:

assign(".trackingSummaryChanged", FALSE, envir = trackingEnv)
assign(".trackingPid", Sys.getpid(), envir = trackingEnv)
if (!is.element("track.auto.monitor", getTaskCallbackNames())) 
    addTaskCallback(track.auto.monitor, name = "track.auto.monitor")
return(invisible(NULL))

我认为,这在 RStudio 和 R.NET 中无法正常工作

PPS 我使用 R 3.2.2 x64、RStudio 0.99.489 和 Windows 10 Pro x64。在 RRO 上,这个问题在 R.NET 和 RStudio 下也存在

4

1 回答 1

1

addTaskCallback()将添加一个在 R 执行返回顶层时执行的回调。当您逐行执行代码时,执行的每个语句都会将控制权返回到顶层,并且会执行回调。

在 内执行时source(),直到调用返回时才source()返回控制,因此回调只运行一次。

于 2015-11-25T04:29:15.220 回答