简体   繁体   English

R 中 system() 和 system2() 的区别? 在变量中捕获文件名

[英]Difference Between system() and system2() in R? Capture File Names in Variable

In R, I wanted to list files in a directory, and capture the output, but there were two calls to the system from R: system() and system2().在 R 中,我想列出目录中的文件,并捕获输出,但是 R 有两个对系统的调用:system() 和 system2()。 I was curious what the differences were, if any, and more importantly how to use them.我很好奇有什么区别,如果有的话,更重要的是如何使用它们。 There were some pages I found, includinghere and here , but I wanted to put some examples here, and the errors I encountered using system2(), including:我找到了一些页面,包括这里这里,但我想在这里放一些例子,以及我在使用 system2() 时遇到的错误,包括:

sh: 1: ls /home : not found sh: 1: ls /home : 未找到

Prior to research, my first tries were all done in system() , as I didn't know about system2() .在研究之前,我的第一次尝试都是在system() ,因为我不知道system2() I decided to redo my method in system2() for portability (I'm working on a Linux system).我决定在system2()重做我的方法以实现可移植性(我在 Linux 系统上工作)。 This led me to find a few differences.这让我发现了一些差异。

First, system() solution to list files and save the output in a variable:首先, system()解决方案列出文件并将输出保存在变量中:

gseaDirectory<-"/home"
filenames<-system(paste("ls", gseaDirectory, sep=" "), intern=T)

This stores a character string "/home", which is where my home directory is, into a variable gseaDirectory.这将我的主目录所在的字符串“/home”存储到变量 gseaDirectory 中。 I then was able to paste in the command ls , a space, sep=" " , and my directory variable gseaDirectory into a linux command to list all files in the chosen directory:然后我能够将命令ls 、一个空格、 sep=" "和我的目录变量gseaDirectory到一个 linux 命令中,以列出所选目录中的所有文件:

ls /home

The list of files is then saved in the variable "filenames" with the added system() argument intern=T .然后将文件列表保存在变量 "filenames" 中,并添加了 system() 参数intern=T

This doesn't work in system2(), and just returns the error:这在 system2() 中不起作用,只会返回错误:

sh: 1: ls /home : not found sh: 1: ls /home : 未找到

Our same method is changed slightly, with the equivalent system2() command being:我们相同的方法略有变化,等效的system2()命令是:

gseaDirectory<-"/home"
filenames<-system2('ls',  paste(gseaDirectory, sep=" "), stdout = TRUE)

The first item in system2 is the command, then the target file, followed by stdout=T which tells R we are going to store the output into a variable, otherwise the result of our command will be printed rather than saved. system2 中的第一项是命令,然后是目标文件,然后是stdout=T ,它告诉 R 我们将把输出存储到一个变量中,否则我们的命令的结果将被打印而不是保存。

Hope this helps someone!希望这可以帮助某人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM