有没有办法在RStudio中测试和查看markdown的选定部分的输出?似乎您要么运行R代码,要么必须编译整个RMD页面才能看到输出。
这是一个仅限Windows的解决方案,它使用剪贴板而不是当前选择:
定义以下功能:
preview <- function() {
output <- tempfile(fileext = ".html")
input <- tempfile(fileext = ".Rmd")
writeLines(text = readClipboard(), con = input)
rmarkdown::render(input = input, output_file = output)
rstudioapi::viewer(output)
}
然后,复制要预览的标记并运行preview()
。注意,输出可能与最终文档中的输出不同,因为
- 代码是在当前环境中评估的
- 只计算复制的markdown,这意味着该片段没有任何上下文
不使用剪贴板的解决方案很可能使用rstudioapi::getActiveDocumentContext()
。它可以归结为类似于修改的preview
函数的东西
preview2 <- function() {
code <- rstudioapi::getActiveDocumentContext()$selection
# drop first line
# compile document (as in preview())
# stop execution (THIS is the problem)
}
它可以通过运行preview()
,然后进行标记来渲染:
preview2()
The value of pi is `r pi`.
问题是,我看不出在调用preview2()
以阻止R尝试解析The value of …
之后如何停止执行。请参阅此相关讨论。