7

我环顾了一下让我感到困惑的地方,我只发现了这一点: 某些程序不接受输入文件的进程替换吗?

这部分有帮助,但我真的很想了解完整的故事。我注意到当我使用进程替换时,我的一些 R 脚本会给出不同的(即错误的)结果。

我试图用一个测试用例来查明问题:

这个脚本:

#!/usr/bin/Rscript

args  <- commandArgs(TRUE)
file  <-args[1]
cat(file)
cat("\n")
data <- read.table(file, header=F)
cat(mean(data$V1))
cat("\n")

使用以这种方式生成的输入文件:

$ for i in `seq 1 10`; do echo $i >> p; done
$ for i in `seq 1 500`; do cat p >> test; done

导致我这样做:

$ ./mean.R test
test
5.5

$ ./mean.R <(cat test)
/dev/fd/63
5.501476

进一步的测试表明有些行丢失了......但我想了解原因。read.table (scan 给出相同的结果) 使用 seek 吗?

附言。使用较小的测试文件 (100) 会报告错误:

$./mean.R <(cat test3)
/dev/fd/63
Error in read.table(file, header = F) : no lines available in input
Execution halted

添加#1:使用使用扫描的修改脚本,结果是相同的。

4

1 回答 1

9

I have written this general purpose function for opening a file connection in my own scripts:

OpenRead <- function(arg) {

   if (arg %in% c("-", "/dev/stdin")) {
      file("stdin", open = "r")
   } else if (grepl("^/dev/fd/", arg)) {
      fifo(arg, open = "r")
   } else {
      file(arg, open = "r")
   }
}

In your code, replace file with file <- OpenRead(file) and it should handle all of the below:

./mean.R test
./mean.R <(cat test)
cat test | ./mean.R -
cat test | ./foo.R /dev/stdin
于 2013-04-03T11:14:14.223 回答