首页 > 解决方案 > 如何获得更短的运行时间?

问题描述

num<-18.7
guess<- -1

print("Can you guess the daily dose per 1000 inhabititants in the UK?")

while(guess !=num) {
    guess<-readline(prompt = "Enter integer:")
    if (guess== num)
        cat(num, "is correct")
    if (guess<num)
        cat("it is bigger")
    if (guess>num)
        cat("It is smaller")
}

当我通过 r 脚本播放它时它可以工作,但是当我将它编织到 markdown 中时,它不会出现错误或任何东西,但它已经运行了大约 30 分钟,但仍未完成。有没有办法改变这个?

标签: rr-markdownknitr

解决方案


正如评论中提到的,R Markdown 文档中的 R 代码是在编织时执行的,而不是在查看时执行的。在谈论 R 的交互性时,人们通常会想到Shiny。在某些情况下,也可以将 Shiny 直接与 R Markdown 结合使用,参见https://bookdown.org/yihui/rmarkdown/shiny-documents.html。脚本的直接转换给出:

---
runtime: shiny
output: html_document
---

# Can you guess the daily dose per 1000 inhabititants in the UK?

```{r setup, include=FALSE}
num <- 18.7
```


```{r guessing-game, echo=FALSE}
numericInput("guess", label = "Enter number:", value = 0)

renderText({
    if (input$guess == num)
        paste(num, "is correct")
    else if (input$guess<num)
        "it is bigger"
    else if (input$guess>num)
        "It is smaller"
})
```

这样的文档可以在本地运行或部署。顺便说一句,==不是比较浮点数的最佳选择。最好使用isTRUE(all.equal())

> 0.3 == 0.1 + 0.1 + 0.1
[1] FALSE
> isTRUE(all.equal(0.3, 0.1 + 0.1 + 0.1))
[1] TRUE

推荐阅读