在R jupyter笔记本中使用ipython magics?

时间:2016-02-09 17:37:14

标签: r jupyter-notebook jupyter-irkernel

我使用conda install jupyter安装了jupyter,并且运行了一个安装了conda create -n my-r-env -c r r-essentials

的r kernal的笔记本

我正在运行一个笔记本,并希望从shell运行bash命令。

!echo "hi"
Error in parse(text = x, srcfile = src): <text>:1:7: unexpected string constant
1: !echo "hi"

为了比较,在带有python内核的笔记本中:

!echo "hi"
hi

有没有办法设置R笔记本具有与ipython笔记本相同的功能关于bash命令(以及其他魔法)?

2 个答案:

答案 0 :(得分:8)

对于bash命令,可以让系统命令工作。例如,在IRkernel中:

system("echo 'hi'", intern=TRUE)

输出:

'hi'

或者查看文件的前5行:

system("head -5 data/train.csv", intern=TRUE)

由于IPython魔法在IPython内核中可用(但不在IRkernel中),我快速检查了是否可以使用rPythonPythonInR库访问这些内容。但是,问题是get_ipython()对Python代码不可见,因此以下都不起作用:

library("rPython")
rPython::python.exec("from IPython import get_ipython; get_ipython().run_cell_magic('writefile', 'test.txt', 'This is a test')")

library("PythonInR")
PythonInR::pyExec("from IPython import get_ipython; get_ipython().run_cell_magic('head -5 data/test.csv')")

答案 1 :(得分:0)

可以通过将调用包装在system中并指定cat作为分隔符来获得'\n'输出的外观改进,该分隔符在单独的行上显示输出而不是分隔空格,这是字符向量的默认值。这对于像tree这样的命令非常有用,因为输出格式没有意义,除非被换行符分隔。

将以下内容与名为test的示例目录进行比较:

<强>击

$ tree test
test
├── A1.tif
├── A2.tif
├── A3.tif
├── README
└── src
    ├── sample.R
    └── sample2.R

1 directory, 6 files

R在Jupyter笔记本中

system,难以理解输出:

> system('tree test', intern=TRUE)

'test' '├── A1.tif' '├── A2.tif' '├── A3.tif' '├── README' '└── src' '    ├── sample.R' '    └── sample2.R' '' '1 directory, 6 files

cat + system,输出看起来像bash:

> cat(system('tree test', intern=TRUE), sep='\n')

test
├── A1.tif
├── A2.tif
├── A3.tif
├── README
└── src
    ├── sample.R
    └── sample2.R

1 directory, 6 files

请注意,对于像ls这样的命令,上面会引入一个换行符,其中输出通常用bash中的空格分隔。

您可以创建一个函数来为您节省一些输入:

> # "jupyter shell" function
> js <- function(shell_command){
>     cat(system(shell_command, intern=TRUE), sep='\n')
> }
>
> # brief syntax for shell commands
> js('tree test')
相关问题