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, including here 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With