height of stringr::str_view output in Rmarkdown

156 views Asked by At

When the output of the stringr::str_view() is printed in a slidy presentation it pushes the subsequent text down. I would like to have the text just after the output of the stringr::str_view() call. I can make the text come right after the stringr::str_view() output by setting sizingPolicy$knitr$figure <- TRUE for the object created by the stringr::str_view() function and also specifying the fig.height in the chunk option. Is there an easier way to avoid the sebsequent text/code is pushed down in the slidy presentation after running stringr::str_view(), without I have to manually set fig.height and sizingPolicy$knitr$figure <- TRUE each time?

I use R version 4.0.2 on a 64 bit machine with a windows 10 platform.

This code generates the problem:

 ---
title: 'An example'
output:
  slidy_presentation
---

```{r}
library(tidyverse)
library(htmlwidgets)
```

```{r}
x <- c("apple", "banana", "pear")
pattern <- "an"
```

```{r}
str_view(x, pattern)
```

Here some text.

This code solves the problem, but I have to manually set the height of the figure and the sizing policy each time:

  ---
title: 'An example'
output:
  slidy_presentation
---

```{r}
library(tidyverse)
library(htmlwidgets)
```

```{r}
x <- c("apple", "banana", "pear")
pattern <- "an"
```

```{r, fig.height=2}
thewidget <- str_view(x, pattern)
thewidget$sizingPolicy$knitr$figure <- TRUE
thewidget
```

Here some text.
1

There are 1 answers

0
Kat On

I tried many different things, but only one way worked—using JS. You can add this chunk anywhere in your RMD; I would suggest keeping it at the end. This will change the sizing to make the blocks 'fit' what's inside them. This works for most browsers.

This will adjust anything rendered as an htmlwidget (like the output from str_view to be sized this way throughout the slide deck.

You don't have to do anything special, like add any particular libraries to make this work. However, it won't do anything if you try to run the chunk inline (instead of knitting).

```{r IwinERRR,results="as-is",engine="js"}

tellMe = document.querySelectorAll('div.html-widget');

for(i = 0; i < tellMe.length; i++){
  tellMe[i].style.width = 'fit-content'; // works for browsers other than IE
  tellMe[i].style.height = 'fit-content';
}

```

I added two of your str_view(x, pattern) chunks to the same slide with the heading 'EEk', this was what was returned when using the JS:

enter image description here