9

I have a variable with html code.

Here what the code variable outpout in R console:

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>

<p>My first paragraph.</p>

</body>
</html>

I try to save the content into a txt file

 write.table(code, file='C:/Users/Desktop/code_result.txt')

But it stacks with this error:

Error in as.data.frame.default(x[[i]], optional = TRUE) : 
  c("cannot coerce class \"c(\"HTMLInternalDocument\", \"HTMLInternalDocument\", \"XMLInternalDocument\", \" to a data.frame", "cannot coerce class \"\"XMLAbstractDocument\")\" to a data.frame")
Berbery
  • 297
  • 2
  • 4
  • 12

4 Answers4

9

Here is a simple solution (although I prefer using package XML as suggested in the comments to your question):

code <- "<!DOCTYPE html>
  <html>
  <body>

  <h1>My First Heading</h1>

  <p>My first paragraph.</p>

  </body>
</html>"

NOTE: if you already have an object containing the text above, you can convert it to a character string so the code below applies:

code <- paste(as.character(code), collapse = "\n")

write.table(code, 
            file='C:/Users/dsargsy/Desktop/code_result.html', 
            quote = FALSE,
            col.names = FALSE,
            row.names = FALSE)
Davit Sargsyan
  • 1,264
  • 1
  • 18
  • 26
5

One option is saveXML and another is sink():

pacman::p_load(scrapeR) # or require() or library()
f = system.file("exampleData", "mtcars.xml", package="XML")
doc = xmlTreeParse(f, useInternalNodes = TRUE)
sink("your.file.txt")
doc
sink()
Hack-R
  • 22,422
  • 14
  • 75
  • 131
2

very comfortable package for all read/write actions is the rio package.

library(rio)
export(html_code,
       file="html_code_result.html",
       format="html"
      )

in this syntax, the rio::export() function supports many other formats, including

  • excel
  • matlab
  • spss
  • json

and many more. It's also very fast!

Agile Bean
  • 6,437
  • 1
  • 45
  • 53
2

The simplest solution using only base would have to be:

writeLines(text = code, con = 'C:/Users/Desktop/code_result.txt')
Inhabitant
  • 859
  • 6
  • 6