[英]How can we read an R variable from JS chunk?
Hello guys any idea how to read an R variable from JS chunk ? 大家好,您知道如何从JS块读取R变量吗?
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 我试图将R变量保存在一个txt文件中,然后从JS块中读取它,但是我不知道怎么做,因为它不起作用
This depends on how complicated you want things to be. 这取决于您希望事情变得多么复杂。
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. 最简单的解决方案就是我在评论中所说的:只需使用内联R代码将值直接作为文本的一部分放入Javascript中即可。 This doesn't work if the Javascript is in a chunk, only if it is in raw
<script></script>
form. 如果Javascript处于大块中,则仅当它以原始
<script></script>
形式时,这才行不通。 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>
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. 更复杂的版本将涉及编写
htmlwidget
,这有点棘手,但是如果您希望R代码响应用户查看网页,则允许在打印R对象时执行任意Javascript代码,或者执行Shiny。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.