我想在Rnw文件和交互式 Shiny 的R markdown文档的两个位置中运行R代码。
因此,由于交互式 Shiny 组件在Rnw文件中不起作用,我需要的是R中的一个代码片段,用于检测是否加载交互式代码。
这似乎可行,但是感觉就像是一个快速的hack:
if (exists("input")) { # input is provided by shiny
# interactive components like renderPlot for shiny
} else {
# non-interactive code for Rnw file
}
是否有一个稳定的解决方案或我可以访问的全局变量之类的信息,该信息指示当前是否正在运行Shiny?还是应该检查
shiny
包是否已加载?最安全的是什么?
最佳答案
这些信息是通过Shiny的 isRunning
function直接提供的。
以下是过时的答案:
您可以执行以下操作:
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应用程序运行。discussion on Shiny the mailing list表示,这可能是(接近)最好的方法-但请注意讨论中提到的警告。
改编自code in the “modules” package。
或者,以下工作。它可能更适合Shiny/RMarkdown用例,但需要存在YAML优先事项:它通过从中读取
runtime
值来工作。shiny_running = function ()
identical(rmarkdown::metadata$runtime, 'shiny')
关于r - 检测是否 Shiny 运行R代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32806974/