Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

system

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

like image 321
kana Avatar asked Feb 04 '18 07:02

kana


1 Answers

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!

like image 72
kana Avatar answered Sep 28 '22 17:09

kana