【发布时间】:2017-03-03 11:42:28
【问题描述】:
我想将 python 与 knitr 一起使用。但是,python 块似乎是单独评估的,并且块之间的变量定义丢失了。
如何解决这个问题?
小例子:
test.pymd
---
title: "Minimal example"
---
With a print statement.
```{r hello}
x = 'Hello, Python World!'
print(x)
```
Without a print statement.
```{r world}
print(x)
```
test.md
---
title: "Minimal example"
---
With a print statement.
```python
x = 'Hello, Python World!'
print(x)
```
```
Hello, Python World!
```
Without a print statement.
```python
print(x)
```
```
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'x' is not defined
```
knit2py.r
#! /usr/bin/Rscript --vanilla
args <- commandArgs(TRUE)
if(length(args) < 1) {
message("Need arguments in the format: %.pymd [%.md]")
q(status=1)
}
name <- substr(args[1],1,nchar(args[1])-4)
if(length(args) < 2) {
args[2] <- paste0(name,".md")
}
library(knitr)
opts_chunk$set(engine = 'python')
res <- try(knit(args[1], args[2]))
if(inherits(res, "try-error")) {
message("Could not successfully knit RMD (or PYMD) to MD")
q(status=1)
} else q()
现在运行:
./knit2py.r test.pymd test.md
【问题讨论】:
-
您是否已经尝试过此链接? stackoverflow.com/questions/30175948/…
-
这将在不久的将来得到改进。目前,大多数非 R 块是相互独立的,并且变量不会持续存在。
-
@YihuiXie 这里有更新吗?我想我在最近的 RStudio 版本之一中记得这些方面的内容
-
@MichaelChirico 是的:github.com/yihui/knitr/issues/1440