问题描述
大家好,知道如何从 JS 块中读取 R 变量吗?
Hello guys any idea how to read an R variable from JS chunk ?
我试图将 R 变量保存在一个 txt 文件中,然后从 JS 块中读取它,但我不知道怎么做,因为它不起作用
I tried to save the R variable on a txt file then read it from the JS chunk but I could not figure out how because it was not working
推荐答案
这取决于您希望事情有多复杂.
This depends on how complicated you want things to be.
最简单的解决方案就是我在评论中所说的:只需使用内联 R 代码将值作为文本的一部分直接放入 Javascript 中.如果 Javascript 位于块中,则这不起作用,仅当它处于原始 </script>
形式时.例如,
The simplest solution is what I said in the comment: just use inline R code to put values directly into the Javascript as part of your text. This doesn't work if the Javascript is in a chunk, only if it is in raw <script></script>
form. For example,
---
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
msg <- "This doesn't work."
```
```{javascript}
alert("`r msg`")
```
```{r}
msg <- "This works: this is a message from R!"
```
<script>
alert("`r msg`")
</script>
更复杂的版本将涉及编写 htmlwidget
,这有点棘手,但允许在打印 R 对象时执行任意 Javascript 代码,或者如果需要 R 代码,则转到 Shiny响应浏览网页的用户.
More complicated versions would involve writing an htmlwidget
, which is a bit tricky but allows arbitrary Javascript code to be executed when you print an R object, or going to Shiny, if you want the R code to respond to the user viewing the web page.
这篇关于我们如何从 JS 块中读取 R 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!