2017-03-04 53 views
1

根据:https://yihui.name/knitr/demo/engines/许多语言由Rmarkdown处理。仅在R块时会继承前面块的变量(R markdown)

但是,我注意到只有R!块似乎继承了以前块的变量。

例如,以下.Rmd文件:

--- 
title: "Variables inheritance in next chunk" 
output: pdf_document 
--- 

## Set variable 

```{r defineVector} 
w = as.vector(c(2,6,7,5,7,8,5,7,6)) 
``` 

## Print mean 

```{r meanValue, echo=TRUE} 
mean(w) 
``` 

编译以及:

variables inherited for R code

但用于Python确切对方(Python的组块的代替数据块 - [R):

--- 
title: "Variables inheritance in next chunk" 
output: pdf_document 
--- 

## Set variable 

```{python defineVector} 
w=[2,6,7,5,7,8,5,7,6] 
``` 

## Print mean 

```{python meanValue, echo=TRUE} 
# Following line results in: <module> NameError: name 'w' is not defined 
print(sum(w)/float(len(w))) 
# However if I repeat line: w=[2,6,7,5,7,8,5,7,6] 
# before print, document works - compiles to PDF 
``` 

给出一个错误(NameError:name'w'is not define d):

error for Python chunk

是否有任何选项来设置所有块到行为完全适用于所有语言一样吗?

回答

2

答案实际上是由OP提供的链接:https://yihui.name/knitr/demo/engines/(我的重点)

Except engine='R' (default), all chunks are executed in separate sessions, so the variables cannot be directly shared. If we want to make use of objects created in previous chunks, we usually have to write them to files (as side effects). For the bash engine, we can use Sys.setenv() to export variables from R to bash (example). Another approach is to use the (experimental) runr package.

下面是一个runr package暗角。

+1

可怜的python支持是一个长期存在的问题,我打算在新的[reticulate](https://github.com/rstudio/reticulate)包裹(未来)使用。 –