等待R中的先前代码块完成。确保它在继续

时间:2017-08-17 11:25:09

标签: r ggplot2 rstudio

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)但它不起作用。我认为执行命令迭代可能与它有关。

1 个答案:

答案 0 :(得分:0)

到目前为止我最好的镜头:

  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秒,但非常复杂的图可能会花费大量时间。