【问题标题】:Wait for completion of previous code chunk in R. Make sure it completes before proceeding等待 R 中上一个代码块的完成。在继续之前确保它完成
【发布时间】:2017-08-17 11:25:08
【问题描述】:

有没有办法让 R 等待第一个块完成后再进行第二个块?或者确保它在进入下一行之前完成?

几乎完整的可重现代码在这里:ggplot piecharts on a ggmap: labels destroy the small plots

代码在 ggmap 上生成小的 ggplots。如果逐块执行,效果很好。但是,如果我运行整个代码,它将无法生成绘图。

当我重新启动代码的第一部分时,我终于得到了之前发生的消息:

Warning message:
In unit %in% c("grobx", "groby", "grobwidth", "grobheight", "grobascent",  :
  reached elapsed time limit

我看到我不能同时运行下面的代码块,我需要运行第一个,看到光标提示表明我可以继续下一个:

df.grobs <- df %>% 
  do(subplots = ggplot(., aes(1, sales, fill = component)) + 
       geom_bar(position = "stack", alpha = 0.5, colour = "white", stat="identity") + 
       geom_text( aes(label = round(sales), y=sales), position = position_stack(vjust = 0.5), size = 2.5)  +
       coord_polar(theta = "y") + 
       scale_fill_manual(values = c("green", "red"))+
       theme_void()+ guides(fill = F)) %>% 
  mutate(subgrobs = list(annotation_custom(ggplotGrob(subplots), 
                                           x = lon-Potential_Sum/300, y = lat-Potential_Sum/300, 
                                           xmax = lon+Potential_Sum/300, ymax = lat+Potential_Sum/300))) 



df.grobs %>%
{p + 
    .$subgrobs + 
            #geom_text(data=df, aes(label = round(Potential_Sum,0)), size=2.5) + 
            geom_col(data = df,
             aes(0,0, fill = component), 
             colour = "white")+ geom_text(data=df, aes(label = Miasto),nudge_y = -0.15, size=2.5)}

我认为 R 不会等待第一个块完成并继续执行第二个。如何确保第一个块完成并等待第二个块的执行?我尝试了各种解决方案来使脚本交互或等待 sys.sleep(1) 但它不起作用.我认为 do 命令迭代可能与此有关。

【问题讨论】:

  • {} 之间插入是否有效?
  • 第二块?在 {} 之间不使用它是行不通的。

标签: r ggplot2 rstudio


【解决方案1】:

迄今为止我最好的一击:

  Delay <- function(wait = 1000) {
    n <- as.numeric(Sys.time()) + wait / 1000
    while (as.numeric(Sys.time()) < n) {}
  }

  plot(graph)
  ### Time-out to finish preview of plot
  Delay(some time in milliseconds)
  ### Plot to file if result is OK
  sel_yesno <- tk_messageBox(type = "yesno", paste("Save plot to file?"))

一个简单的 ggplot 似乎需要大约 1.5 秒,但非常复杂的绘图可能需要大量额外的时间。

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    相关资源
    最近更新 更多