Piping stdin to R

后端 未结 3 2128
日久生厌
日久生厌 2020-12-01 08:12

I am having trouble piping stdin to an R script.

Here is my toy script test.R:

#!/usr/bin/env Rscript
while(length(line <- readLines(         


        
相关标签:
3条回答
  • 2020-12-01 08:30

    This is the easiest I've found (assuming numeric input):

    x <- scan(file("stdin")
    

    you can test it with:

    $ echo -e "1\n2\n3" | R -s -e 'x <- scan(file("stdin")); summary(x)'
    Read 3 items
       Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
        1.0     1.5     2.0     2.0     2.5     3.0 
    
    0 讨论(0)
  • 2020-12-01 08:32

    Jeff and I wrote littler to do just this (and a few other things). Because of littler, I never looked that closely at Rscript -- but this should in principle work just fine.

    Here is one of our early examples, using output from /bin/ls (and a quick filter by awk) to summarize file size:

    edd@max:~/svn/littler/examples$ ls -l /boot/ | \
                                        awk '!/^total/ {print $5}' | ./fsizes.r 
        Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
          24   130300   730700  3336000  4527000 14670000 
    
      The decimal point is 6 digit(s) to the right of the |
    
       0 | 0000000000000011111111122777777777
       2 | 777777777
       4 | 555577777
       6 | 
       8 | 
      10 | 
      12 | 5
      14 | 24466677
    
    edd@max:~/svn/littler/examples$ 
    

    Here the script fsizes.r is just three lines:

    edd@max:~/svn/littler/examples$ cat fsizes.r 
    #!/usr/bin/r -i
    
    fsizes <- as.integer(readLines())
    print(summary(fsizes))
    stem(fsizes)
    edd@max:~/svn/littler/examples$ 
    
    0 讨论(0)
  • 2020-12-01 08:44

    This does not happen if you explicitly open the stdin connection.

    #!/usr/bin/env Rscript
    f <- file("stdin")
    open(f)
    while(length(line <- readLines(f,n=1)) > 0) {
      write(line, stderr())
      # process line
    }
    
    0 讨论(0)
提交回复
热议问题