r - 如何获得更短的运行时间?
问题描述
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 分钟,但仍未完成。有没有办法改变这个?
解决方案
正如评论中提到的,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
推荐阅读
- sql - 将周六和周日日期替换为上周五日期
- python - Pandas / 如何将存储为字符串的科学记数法转换为浮点数?
- python - 多对多查询的正确方法(django)
- vba - 硒 VBA 铬
- spring-boot - 如何删除有关 conluent.monitoring.interceptor 的警告?
- python - 使用 Python 在数据集中的位置之间分离相同的 ID 值
- windows-10 - 如果将任务管理器替换为 SysInternals Process Explorer,如何在 Windows 10 中添加启动应用程序?
- javascript - 如何在按钮单击时获取文本区域的随机值
- javascript - 如何相互隔离编译 TypeScript 文件?
- testing - 如果“设置测试”失败,Spock 会忽略测试