在R jupyter笔记本中使用ipython魔法?

20

我使用conda install jupyter安装了Jupyter,并从conda create -n my-r-env -c r r-essentials安装r内核。

我正在运行一个笔记本,并希望从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
看起来似乎不可能:https://github.com/IRkernel/IRkernel/issues/244 - elsherbini
2个回答

16

对于仅限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')")

5
使用cat函数将system的输出结果包裹,并指定分隔符为'\n',可以使输出更加美观,而不是像字符向量一样使用空格作为默认分隔符进行分隔。这对于像tree这样的命令非常有用,因为除非使用换行符进行分隔,否则输出格式几乎没有意义。
以名为test的示例目录为比较对象,请参考以下内容: Bash
$ tree test
test
├── A1.tif
├── A2.tif
├── A3.tif
├── README
└── src
    ├── sample.R
    └── sample2.R

1 directory, 6 files

Jupyter Notebook 中的 R

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')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接