使用
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中输出通常由空格分隔的地方引入一个换行符。
您可以创建一个函数来节省一些输入。
>
> js <- function(shell_command){
> cat(system(shell_command, intern=TRUE), sep='\n')
> }
>
>
> js('tree test')