Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 288
Geek Avatar asked Nov 01 '25 08:11

Geek


1 Answers

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.

like image 93
user2554330 Avatar answered Nov 02 '25 22:11

user2554330