Canovice Canovice - 1 month ago 12x
MySQL Question

R - running commands in terminal and saving output to a dataframe

On OSX, I am using the system() function to run commands in terminal from the R console as part of a script I've written. The script requires connecting to a MySQL() database through an ssh tunnel, and I type into the command line "ps aux | grep ssh" to see what tunnels i am connected to. For example, some output:


> system("ps aux | grep ssh")
Home 50915 0.0 0.0 2501204 3264 ?? S 10:32AM server info
Home 50092 0.0 0.0 2504172 3048 ?? Ss 9:35AM server2 info
Home 50090 0.0 0.0 2501372 480 ?? Ss 9:35AM server3 info
Home 1155 0.0 0.0 2544220 1368 ?? S Thu07PM server4 info
Home 51333 0.0 0.0 2434840 800 ?? S 11:00AM 0:00.00 grep ssh
Home 51331 0.0 0.0 2438508 1124 ?? S 11:00AM 0:00.00 sh -c ps aux | grep ssh


I would like to turn this output into a dataframe, but cannot. Functions like"ps aux | grep ssh"))
do not work as how I would hope them to work.

Any thoughts on this would be appreciated!

EDIT - just wanted to highlight error from one suggested comment

> read.table(pipe("ps aux | grep ssh"))
Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec, :
line 1 did not have 34 elements
> pipe("ps aux | grep ssh")
description class mode text opened can read can write
"ps aux | grep ssh" "pipe" "r" "text" "closed" "yes" "yes"


First pipe your output to an actual text file:

> system("ps aux | grep ssh") > output.txt

Then read in this file into R using read.table:

df.output <- read.table(file="output.txt", header=FALSE, sep="")

Note: Using sep="" (which is the default for read.table actually) will treat any type/amount of whitespace as a delimeter between columns. This should cover the output you are getting from your call to Linux.