简体   繁体   中英

R - Writing a Matrix to an Output File With a Title and Footnote

Currently I am doing a very custom job in R where I am populating a big matrix with values that are computed before. I send the matrix to an external file with the following:

write.csv(m1, file = "OutputToExcel1.csv")

... where m1 is my matrix of interest and I already set an appropriate working directory.

I would like to give it a descriptive title and possibly a footnote. In searching for a solution there appear to be many commands besides write.csv.

Can anyone recommend an easy & standard & easy way to do this besides sink()?

If you don't want to use sink() , you can use file() connection and write.csv() between your writeLines() statements, but it looks like you have to wrap write.csv() with capture.output() , which is very similar to sink() .

Example data:

# matrix for reproducible example
data("Harman74.cor")

dest_file <- "OutputToExcel1.csv"

The trick seems to be to use file(..., open='at') to support multiple appends:

if(file.exists(dest_file)) file.remove(dest_file) # need empty file before append

fileConn<-file(dest_file, open='at')
write("Descriptive Title", file = fileConn)
write( capture.output(write.csv(Harman74.cor)), 
       file = fileConn, 
       append=TRUE )
write("Helpful footnote", file = fileConn)
close(fileConn)

file.show(dest_file)

If you're not completely set against using sink() , it is pretty straightforward. Taking advantage of the default behavior of write.csv() , which prints to console, you can just redirect this output.

sink(dest_file)
writeLines("Descriptive Title")
cat(write.csv(Harman74.cor))
writeLines("Helpful footnote")
sink()

file.show(dest_file)

The following seems to work, but it:

  • Puts an x in the upper-left of the spreadsheet
  • Gives the number 1 before the title, &
  • Puts the title in quotes.

I think the following might be "good enough?"

setwd("Y:/Zach/")
myfile<-"DSummary.csv"
write.table("Title", myfile)
write.table(m1, myfile, sep=",", col.names=FALSE, append=TRUE)

Below is a more elaborate stating of the above code:

setwd("Y:/Zach/")
myfile<-"DSummary.csv"
write.table("Title1: n = ", myfile)
write.table(SchoolCnt, myfile, col.names=FALSE, append=TRUE)
write.table(". Is good enough", col.names=FALSE, append=TRUE)
write.table(m1, myfile, sep=",", col.names=FALSE, append=TRUE)

So the way I am breaking up standard text strings and variables is very sloppy. Any suggestions on how I may concatenate them would be awesome!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM