简体   繁体   中英

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(). 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:

sh: 1: ls /home : not found

Prior to research, my first tries were all done in system() , as I didn't know about system2() . I decided to redo my method in system2() for portability (I'm working on a Linux system). This led me to find a few differences.

First, system() solution to list files and save the output in a variable:

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. 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 /home

The list of files is then saved in the variable "filenames" with the added system() argument intern=T .

This doesn't work in system2(), and just returns the error:

sh: 1: ls /home : not found

Our same method is changed slightly, with the equivalent system2() command being:

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.

Hope this helps someone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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