r - 流程替代

扫码查看

我环顾四周,想知道是什么让我困惑,我只发现了这个:
Do some programs not accept process substitution for input files?
这是部分帮助,但我真的想了解整个故事。
我注意到当我使用进程替换时,我的一些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

Add#1:使用scan的修改脚本的结果是相同的。

最佳答案

我已经用自己的脚本编写了这个用于打开文件连接的通用函数:

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

在代码中,用file替换file <- OpenRead(file),它应该处理以下所有问题:
./mean.R test
./mean.R <(cat test)
cat test | ./mean.R -
cat test | ./foo.R /dev/stdin

关于r - 流程替代,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15784373/

10-11 23:04
查看更多