简体   繁体   中英

How can I save text to a file in R?

I have a R function which can generate the LaTeX code (the output is the LaTex code) by using cat() , while now I want to save these LaTeX code, but I don't know which function can save these LaTeX code...

I like to use the sink() function:

latex.code <- function(){
   cat("\\begin{align}\n")
   cat("[X'X]^{-1}X'y\n")
   cat("\\end{align}\n")
}
sink(file='ols.txt')
latex.code()
sink()

Edit: Obviously, you can choose the file path where the file will be saved by changing the sink argument such as: sink(file='c:/Users/Eva/Desktop/ols.txt') , or sink(file='~/ols.txt')

Assuming your R function returns a character string of LaTeX code (your question would be much improved if you made it more concrete, with some specific examples), you can output something like that to a file using the cat() function, and specifying a file using the file= argument. You can read about it via?cat.

If it happens that you have your output in a character vector (ie you are using something like cat(<something>) to have it written to the console), you can use writeLines function, like this:

writeLines(<something>,"filename.txt")

However the best way to make a LaTeX file in R is to use either Sweave or make a brew template.

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