R Language Reading and writing strings Capture output of operating system command


Example

Functions which return a character vector

Base R has two functions for invoking a system command. Both require an additional parameter to capture the output of the system command.

system("top -a -b -n 1", intern = TRUE) 
system2("top", "-a -b -n 1", stdout = TRUE)

Both return a character vector.

  [1] "top - 08:52:03 up 70 days, 15:09,  0 users,  load average: 0.00, 0.00, 0.00"     
  [2] "Tasks: 125 total,   1 running, 124 sleeping,   0 stopped,   0 zombie"            
  [3] "Cpu(s):  0.9%us,  0.3%sy,  0.0%ni, 98.7%id,  0.1%wa,  0.0%hi,  0.0%si,  0.0%st"  
  [4] "Mem:  12194312k total,  3613292k used,  8581020k free,   216940k buffers"        
  [5] "Swap: 12582908k total,  2334156k used, 10248752k free,  1682340k cached"         
  [6] ""                                                                                
  [7] "  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND            "
  [8] "11300 root      20   0 1278m 375m 3696 S  0.0  3.2 124:40.92 trala              "
  [9] " 6093 user1     20   0 1817m 269m 1888 S  0.0  2.3  12:17.96 R                  "
 [10] " 4949 user2     20   0 1917m 214m 1888 S  0.0  1.8  11:16.73 R                  "

For illustration, the UNIX command top -a -b -n 1 is used. This is OS specific and may need to be amended to run the examples on your computer.

Package devtools has a function to run a system command and capture the output without an additional parameter. It also returns a character vector.

devtools::system_output("top", "-a -b -n 1") 

Functions which return a data frame

The fread function in package data.table allows to execute a shell command and to read the output like read.table. It returns a data.table or a data.frame.

fread("top -a -b -n 1", check.names = TRUE)
       PID     USER PR NI  VIRT  RES  SHR S X.CPU X.MEM     TIME.         COMMAND
  1: 11300     root 20  0 1278m 375m 3696 S     0   3.2 124:40.92           trala
  2:  6093    user1 20  0 1817m 269m 1888 S     0   2.3  12:18.56               R
  3:  4949    user2 20  0 1917m 214m 1888 S     0   1.8  11:17.33               R
  4:  7922    user3 20  0 3094m 131m 1892 S     0   1.1  21:04.95               R

Note, that fread automatically has skipped the top 6 header lines.

Here the parameter check.names = TRUE was added to convert %CPU, %MEN, and TIME+ to syntactically valid column names.