【问题标题】:R - running commands in terminal and saving output to a dataframeR - 在终端中运行命令并将输出保存到数据帧
【发布时间】:2016-08-29 15:06:23
【问题描述】:

在 OSX 上,作为我编写的脚本的一部分,我使用 system() 函数从 R 控制台在终端中运行命令。该脚本需要通过 ssh 隧道连接到 MySQL() 数据库,然后我在命令行中键入“ps aux | grep ssh”以查看我连接到的隧道。例如,一些输出:
.

> 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

.
我想将此输出转换为数据框,但不能。像as.data.frame(system("ps aux | grep ssh")) 这样的函数不能像我希望的那样工作。

对此的任何想法将不胜感激!

编辑 - 只是想突出一条建议评论中的错误

> 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" 

【问题讨论】:

  • 您所拥有的只是需要解析为 data.frame 的原始文本。请改用read.table(pipe("ps aux | grep ssh"))

标签: mysql r macos terminal


【解决方案1】:

首先将您的输出通过管道传输到一个实际的文本文件:

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

然后使用read.table将该文件读入R:

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

注意:使用sep=""(实际上是read.table 的默认值)会将任何类型/数量的空白视为列之间的分隔符。这应该涵盖您从调用 Linux 中获得的输出。

【讨论】:

    【解决方案2】:

    您可以使用intern=TRUE 更接近(接近字符向量):

    as.data.frame(system("ps aux | grep ssh", intern=TRUE))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      相关资源
      最近更新 更多