gpt4 book ai didi

python - 将 python 与 knitr 一起使用

转载 作者:太空狗 更新时间:2023-10-29 21:05:00 25 4
gpt4 key购买 nike

我想将 python 与 knitr 一起使用。然而,python block 似乎是单独评估的,并且变量定义在 block 之间丢失。

如何解决?

最小的例子:

测试.pymd

---
title: "Minimal example"
---

With a print statement.

```{r hello}
x = 'Hello, Python World!'
print(x)
```

Without a print statement.

```{r world}
print(x)
```

测试.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 

最佳答案

是的,确实,knitr 目前无法为 R 以外的语言评估跨多个 block 的代码拉伸(stretch)。解决方案不是使用 knitr,而是使用 pweave。对源文件的修改很少:

测试.mdw

---
title: "Minimal example"
---

With a print statement.

<<>>=
x = 'Hello, Python World!'
print(x)
@

Without a print statement.

<<>>=
print(x)
@

The end.

现在运行:

pweave -f pandoc test.mdw

pweave 上有注释的网站上说使用 python3 的 pip 安装会失败。不过,我在简单运行时完全没有问题:

pip install pweave
pip install markdown

也许,这只是一张旧纸条。

关于python - 将 python 与 knitr 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40171949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com