7

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

oguz ismail
  • 1
  • 16
  • 47
  • 69
kana
  • 605
  • 7
  • 12

1 Answers1

9

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!

kana
  • 605
  • 7
  • 12
  • 1
    In `system` instead of `paste("ls", paste(gseaDirectory), sep=" ")` do `paste("ls", gseaDirectory)` – pogibas Feb 04 '18 at 07:33
  • 1
    You don't need `sep = " "` in `paste` (check difference between `paste` and `paste0`). And this `paste(gseaDirectory, sep=" ")` in `system2` does nothing – pogibas Feb 04 '18 at 08:24
  • 1
    That's great! I think I may leave those there though, since even if they don't do anything they may spur further inquiry for example subdirectories (sep="/"). This was originally the purpose of the extra pastes, I only simplified it here as an example. – kana Feb 04 '18 at 13:26