[R] Reading several tables from stdin

Julio Sergio juliosergio at gmail.com
Wed Jun 13 22:42:18 CEST 2012


I'm trying to write a Rscript program capable of reading several tables from the 
standard input. The problem is that the tables aren't in files because they are 
coming from another process that is generating them. From the R-console the 
following works pretty well:

  |> f <- stdin()
  |> t <- read.table(f)
  |> t2 <- read.table(f)
  |> t
     uno dos
  01   3   4
  02   5   6
  03   7   8
  |> t2
     uno dos
  01   9  10
  02  11  12
  03  13  14
  
  |> t + t2
     uno dos
  01  12  14
  02  16  18
  03  20  22

Being aware of the differences between stdin(), and file("stdin"), I wrote a 
Rscript program that is aimed at doing the same as the shown interactive 
session:


  #! /usr/bin/Rscript
  f <- file("stdin")
  t <- read.table(f)
  t2 <- read.table(f)
  print (t + t2)

When I try this script, it always ends in error, as follows:

FIRST TRY:
  $ ./addT.R 
  uno dos
  01 3 4
  02 5 6
  03 7 8
             <-I introduced an emtpy line here
  uno dos
  Error en scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
    la linea 4 no tiene 3 elementos
  Calls: read.table -> scan
  Ejecución interrumpida

SECOND TRY
  $ ./addT.R 
  uno dos
  01 3 4
  02 5 6
  03 7 8
             <-I introduced the EOF terminator (^D) here
  Error en isOpen(file, "rt") : conexión inválida
  Calls: read.table -> isOpen
  Ejecución interrumpida


Do you have any comments on this?

Thanks,
-- Sergio.



More information about the R-help mailing list