Combining R + awk + bash commands

前端 未结 2 2082
遥遥无期
遥遥无期 2021-01-05 03:44

I want to combine awk and R language. The thing is that I have a set of *.txt files in a specified directory and that I don\'t know the length of the header from the files.

相关标签:
2条回答
  • 2021-01-05 04:33

    You can use system to run an external program from R.

    system("gawk --version", intern=TRUE)
    
    0 讨论(0)
  • 2021-01-05 04:45

    Besides Vincent's hint of using system("awk ...", intern=TRUE), you can also use the pipe() function that is part of the usual text connections:

    R> sizes <- read.table(pipe("ls -l /tmp | awk '!/^total/ {print $5}'"))
    R> summary(sizes)
           V1          
     Min.   :       0  
     1st Qu.:     482  
     Median :    4096  
     Mean   :   98746  
     3rd Qu.:   13952  
     Max.   :27662342  
    R> 
    

    Here I am piping a command into awk and then read all the output from awk, that could also be a single line:

    R> cmd <- "ls -l /tmp | awk '!/^total/ {sum = sum + $5} END {print sum}'"
    R> totalsize <- scan(pipe(cmd), quiet=TRUE)
    R> totalsize
    [1] 116027050
    R> 
    
    0 讨论(0)
提交回复
热议问题