R和系统调用

时间:2011-04-21 14:59:58

标签: r command-line

我过去使用过R来对命令行进行非常基本的调用。可以找到示例here

这一次,我希望模仿在Windows中从命令行成功运行的代码:

> cd C:\Documents and Settings\BTIBERT\My Documents\My Dropbox\Eclipse\Projects\R\MLB\retrosheet\rawdata
> bgame -y 2010 2010bos.eva >2010bos.txt

这是我试图在R里面运行的代码。我已经在R里面设置了工作目录。

dir <- paste("cd", getwd(), sep=" ")
system(dir)
system("bgame -y 2010 2010bos.eva >2010bos.txt")

我确定这是用户错误,但我做错了什么?它似乎最初工作,但返回以下错误。我很可能做错了,但我相信我使用相同的命令。

Expanded game descriptor, version 109(185) of 05/08/2008.
  Type 'bgame -h' for help.
Copyright (c) 2001 by DiamondWare.
[Processing file 2010bos.eva.]
>2010bos.txt: can't open.
Warning message:
running command 'bgame -y 2010 2010bos.eva >2010bos.txt' had status 2 

您将获得任何帮助。

3 个答案:

答案 0 :(得分:26)

您需要在一次system()电话中发出所有命令:

system(paste("cd",getwd() "&& bgame -y 2010 2010bos.eva >2010bos.txt",sep=" "))

您应该已经在工作目录中了,所以我不确定cd getwd()是否必要。并且您可能需要在路径周围添加引号,因为它包含空格。可以通过在>周围放置空格来解决错误。

如果我在你的鞋子里,我会尝试这个:

system("bgame -y 2010 2010bos.eva > 2010bos.txt")

更新:

你应该注意?system中“{1}}的”与Windows之间的差异“部分中的这个建议,你应该使用shell

    • The most important difference is that on a Unix-alike
      ‘system’ launches a shell which then runs ‘command’.  On
      Windows the command is run directly - use ‘shell’ for an
      interface which runs ‘command’ _via_ a shell (by default the
      Windows shell ‘cmd.exe’, which has many differences from the
      POSIX shell).

      This means that it cannot be assumed that redirection or
      piping will work in ‘system’ (redirection sometimes does, but
      we have seen cases where it stopped working after a Windows
      security patch), and ‘system2’ (or ‘shell’) must be used on
      Windows.

答案 1 :(得分:9)

没有其他人发现system("dir", intern = T)例如无效,但您需要system("cmd.exe /c dir", intern = T)吗?只有后者适合我。我在讨论网站here(威廉邓拉普的帖子,大约三分之一的位置)发现了这一点。

此外,它不能与&#34; cd&#34;命令,但您可以使用R中的setwd()函数,然后该命令将在该目录中执行。

为方便起见,我创建了以下函数,用于执行程序和运行命令:

#the subject is an input file that a programme might require
execute <- function(programme, subject.spec = "", intern = FALSE, wait = FALSE){
  if(!identical(subject.spec, "")){subject.spec <- paste0(" ", subject.spec)} #put space before the subject if it exists
  system(paste0("cmd.exe /c ", programme, subject.spec), intern = intern, wait = wait)
}


command <- function(command, intern = TRUE, wait = FALSE){
  system(paste("cmd.exe /c", command), intern = T, wait = wait)
}

答案 2 :(得分:0)

当您收到错误1或执行继续时,是否会破坏您的代码?

每当通过其他语言执行系统命令时,在调用系统调用之前打印系统调用以查看确切的结果是很有用的,启动您打算使用的shell并检查是否存在相同的错误。当命令正确执行时,这可能是bgame或R中的hickup。

如果查看http://astrostatistics.psu.edu/datasets/R/html/base/html/shell.html,您可以看到传递给系统调用的变量标志。&#34;标记交换机以在shell下运行命令。如果shell是bash或tcsh,则默认值更改为&#34; -c&#34;。&#34;

Also "the shell to be used can be changed by setting the configure variable R_SHELL to a suitable value (a full path to a shell, e.g. /usr/local/bin/bash)."