[R] Linux System Function

Marc Schwartz marc_schwartz at me.com
Sat Apr 24 02:53:06 CEST 2010


On Apr 23, 2010, at 6:07 PM, Ryan Garner wrote:

> 
> How do I pass a filename as an argument to the system command to count the
> number of records in that file? I only know how to do it by hardcoding it.
> 
> HARDCODING EXAMPLE
>> test <- matrix(1:20,ncol=5)
>> write(x = test,file = "test.txt")
>> records <- as.numeric(system("cat test.txt | wc -l",intern = TRUE))
>> records
> [1] 4
> 
> ??? NON-HARCODING EXAMPLE ???
>> file = "test.txt"
>> records <- as.numeric(system("cat file | wc -l",intern = TRUE))
> cat: file: No such file or directory
>> records <- as.numeric(system("cat" test.txt "| wc -l",intern = TRUE))
> Error: unexpected symbol in "records <- as.numeric(system("cat" test.txt"
> 
> TFYH


See ?paste

file <- "test.txt"
cmd <- paste("cat", file, "| wc -l")

> cmd
[1] "cat test.txt | wc -l"

Then use:

as.numeric(system(cmd, intern = TRUE))

HTH,

Marc Schwartz



More information about the R-help mailing list