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

在R jupyter笔记本中使用ipython magics?,r,jupyter-notebook,jupyter-irkernel,R,Jupyter Notebook,Jupyter Irkernel,我使用conda install jupyter安装了jupyter,正在运行一个笔记本,其r内核安装于conda create-n my-r-env-c r-essentials 我正在运行一个笔记本,希望从shell运行bash命令 !echo "hi" Error in parse(text = x, srcfile = src): <text>:1:7: unexpected string constant 1: !echo "hi" 有没有一种方法可以将R笔记本电脑设置为

我使用
conda install jupyter安装了jupyter
,正在运行一个笔记本,其r内核安装于
conda create-n my-r-env-c r-essentials

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

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

有没有一种方法可以将R笔记本电脑设置为与ipython笔记本电脑在bash命令(可能还有其他魔法)方面具有相同的功能?

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

system("echo 'hi'", intern=TRUE)
输出:

'hi'
或查看文件的前5行:

system("head -5 data/train.csv", intern=TRUE)
由于IPython magics在IPython内核中可用(但在IRkernel中不可用),因此我快速检查了是否可以使用
rPython
Pythonir
库访问它们。但是,问题是Python代码看不到
get_ipython()
,因此以下各项都不起作用:

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

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

比较名为
test
的示例目录的以下内容:

Bash

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

1 directory, 6 files
Jupyter笔记本中的R

仅限系统
,难以理解输出:

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

'test' '├── A1.tif' '├── A2.tif' '├── A3.tif' '├── README' '└── src' '    ├── sample.R' '    └── sample2.R' '' '1 directory, 6 files
cat
+
系统
,输出如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')
#“jupyter shell”函数
>js cat(系统(shell_命令,intern=TRUE),sep='\n')
> }
>
>#shell命令的简要语法
>js(‘树测试’)

看起来这是不可能的:
> # "jupyter shell" function
> js <- function(shell_command){
>     cat(system(shell_command, intern=TRUE), sep='\n')
> }
>
> # brief syntax for shell commands
> js('tree test')