简体   繁体   中英

How can we read an R variable from JS chunk?

Hello guys any idea how to read an R variable from JS chunk ?

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.

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM