user2543622
user2543622

Reputation: 6766

linux - running system command in R and then writing output to a file

I have R code as below. Below code resides in a file called 'iot.R'. I am executing it in Linux.

I want to print content of variable 'fileinformation' to a file mentioned by file=fileConn... I thought that the 3rd line will solve the issue, but it is not giving the required output :(

   fileinformation = system(paste("file", filenames[1]))
    #print(fileinformation)
    cat(print(fileinformation),"\r\n","\r\n", file=fileConn)

When I run the file, i get below result. It prints to my screen, rather than writing to the file :(

> source('iot.R')
CH7Data_20130401T135010.csv: ASCII text, with CRLF line terminators
[1] 0

--------------------update1

I also tried below command, but didnt get the expected rsult

cat(capture.output(fileinformation),"\r\n","\r\n", file=fileConn)

Upvotes: 0

Views: 995

Answers (2)

nicola
nicola

Reputation: 24480

You need to set the intern argument to TRUE in your call to system. For instance:

    fileinformation<-system("file cinzia_2.gif",intern=TRUE)
    fileinformation
    #[1] "cinzia_2.gif: GIF image data, version 89a, 640 x 640"

Of course I tried a file on my pc. Setting intern to TRUE the return value of system becomes the console output of the command. Then, when you call cat, you don't need to enclose fileinformation into print, but a simple cat(fileinformation,"\r\n","\r\n", file=fileConn) will suffice.

Upvotes: 2

mattbawn
mattbawn

Reputation: 1378

Hi Just a comment as I dont have enough rep to comment in the normal way. but cant you use

write.table

to save the output to a file? It may be easier?

Upvotes: 0

Related Questions