R 将html结果保存到txt或html文件

R 将html结果保存到txt或html文件,r,R,我有一个带有html代码的变量 下面是R控制台中代码变量输出的内容: <!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html> 但它与这个错误叠加在一起: Error in as.data.frame.default(x[[i]], optio

我有一个带有html代码的变量

下面是R控制台中代码变量输出的内容:

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>

<p>My first paragraph.</p>

</body>
</html>
但它与这个错误叠加在一起:

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")

一个选项是
saveXML
,另一个选项是
sink()

下面是一个简单的解决方案(尽管我更喜欢使用问题注释中建议的包XML):


code对于所有读/写操作来说,非常舒适的包是rio包

library(rio)
export(html_code,
       file="html_code_result.html",
       format="html"
      )
在此语法中,rio::export()函数支持许多其他格式, 包括

  • 胜过
  • matlab
  • spss
  • json
还有更多。
它也很快

仅使用碱的最简单解决方案必须是:

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

使用
saveXML
而不是
write.table
。或者提供一个可复制的示例,否则这将是一个猜测游戏。@Narendra代码是这种格式的html代码
Title
@lukeA saveXML works@lukeA
saveXML()
来自哪个软件包?或者
saveXML
本身就是软件包的名称吗?这段4年的代码完全拯救了我的一周。干杯,伙计!
code <- "<!DOCTYPE html>
  <html>
  <body>

  <h1>My First Heading</h1>

  <p>My first paragraph.</p>

  </body>
</html>"
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)
library(rio)
export(html_code,
       file="html_code_result.html",
       format="html"
      )
writeLines(text = code, con = 'C:/Users/Desktop/code_result.txt')