简体   繁体   English

我们如何从JS块读取R变量?

[英]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.

相关问题 我们可以从 postman 中的 excel 中读取数据以进行 js 测试吗? - Can we read data from excel in postman for js tests? 我们如何使用外部节点js中的函数调用内部变量? - How can we use inner variable from function calling in node js at outside? 我们如何从node.js中的回调函数中访问变量? - How can we access variable from callback function in node.js? 如何读取和删除块中太多未使用的js代码 - how to read and remove too many unused js code in chunk 我们如何在 vue js 中的数据 function 中动态声明变量? - How can we declare a variable dynamically in data function in vue js? 是否可以将一个JS块存储在一个变量中? - Is it possible to store a chunk of JS in a variable? 我们如何从 javascript 变量中获取 php 变量中的值 - How can we get value in php variable from javascript variable 我们如何从数据库(postgres)用jquery读取xml文件? - How we can read xml file with jquery from database (postgres)? 我们如何从赛普拉斯的一个文件夹中读取多个文件? - How can we read multiple files from a folder in Cypress? 我们如何使用javascript从nprinting变量中获取价值 - how we can get value from nprinting variable using javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM