2017-03-04 51 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)包裹(未來)使用。 –