Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rstudioapi::viewer programmatic deletion option

Tags:

r

rstudio

The rstudioapi::viewer can render static html pages from temp directory as given in the following example.

dir <- tempfile()
dir.create(dir)
htmlFile <- file.path(dir, "index.html")
writeLines(
  '<h1 style="text-align: center;">Thank you for using <span style="color: #ff0000;">Tidycells</span></h1>
<p style="text-align: center;">It is an <span style="color: #ff6600;"><strong>assistant</strong> </span>for you</p>
<p style="text-align: center;">It is <span style="text-decoration: underline;">yet to <span style="color: #0000ff; text-decoration: underline;">evolve</span></span></p>',
  htmlFile
)
suppressWarnings(rstudioapi::viewer(htmlFile))    

However, I could not delete a viewer object using R code.

screenshot

enter image description here

If anyone clicks the delete button ("Remove current viewer item") the current item will be deleted.

I was looking for a programmatic way to do it.

Maybe rstudioapi::viewer(htmlFile) will return an id and that can be used to delete the specific item from the viewer pane.

like image 756
Indranil Gayen Avatar asked Mar 09 '26 16:03

Indranil Gayen


1 Answers

I finally did it like this

runApp_nb <- function(sa, pin_port = NULL){


  viewer <- getOption("viewer")
  if(!is.null(viewer)){

    if(!is.null(pin_port) && is.integer(pin_port)){
      port <- pin_port
    }else{
      port <- as.integer(sample(3000:49000, 1))
    }

    x <- callr::r_bg(function(x, y){shiny::runApp(x, port = y)}, args = list(sa , port))
    viewer(paste0("http://localhost:",port,"/"))
    return(invisible(x))
  }

  cat("\nThis is designed for RStudio\n")

  return(invisible(0))

}

Then

x <- runApp_nb(shinyApp(ui = ui, server = server))

Finally after operation

x$kill_tree()
like image 173
Indranil Gayen Avatar answered Mar 11 '26 09:03

Indranil Gayen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!