R code brilliant detection

I would like to run R code in two places, in the Rnw file and as an interactive brilliant R markdown document.

So, what I need, since interactive brilliant components do not work in Rnw files, is a piece of code in R that determines whether to load interactive code or not.

This seems to work, but it looks like a quick hack:

if (exists("input")) { # input is provided by shiny
    # interactive components like renderPlot for shiny
} else {
    # non-interactive code for Rnw file
}

Is there a stable solution or something like a global variable available to me that says if brilliant is currently working? Or should I check if the package is downloaded shiny?

Which is safer?

+4
source share
2 answers

You can do the following:

shiny_running = function () {
    # Look for `runApp` call somewhere in the call stack.
    frames = sys.frames()
    calls = lapply(sys.calls(), `[[`, 1)
    call_name = function (call)
        if (is.function(call)) '<closure>' else deparse(call)
    call_names = vapply(calls, call_name, character(1))

    target_call = grep('^runApp$', call_names)

    if (length(target_call) == 0)
        return(FALSE)

    # Found a function called `runApp`, verify that it’s Shiny’s.
    target_frame = frames[[target_call]]
    namespace_frame = parent.env(target_frame)
    isNamespace(namespace_frame) && environmentName(namespace_frame) == 'shiny'
}

shiny_running() , , Shiny.

, , () , Shiny - , .

"modules" .

, . Shiny/RMarkdown, YAML: , runtime .

shiny_running = function ()
    identical(rmarkdown::metadata$runtime, 'shiny')
+2

: Konrad Rudolphs . .

Konrad Rudolphs , , OPs. :

if (identical(rmarkdown::metadata$runtime, "shiny")) {
  "shinyApp" 
} else {
  "static part"
}

, . .Rmd runtime: shiny YAML, , , .

, , , , .


, , :

document_is_interactive <- TRUE

if (document_is_interactive) {
    # interactive components like renderPlot for shiny
} else {
    # non-interactive code for Rnw file
}

, , rmarkdown::metadata$runtime.

+2

Source: https://habr.com/ru/post/1609168/


All Articles