R语言 | 如何使用R书写html文档?
更灵活的书写方式,可以直接看3.
1. 可用函数
- cat()函数
- writeLines()函数
- sink()函数重定向输出到HTML文件
小结:cat()适合简单HTML,writeLines()适合多行内容,sink()适合复杂场景。
说明:尽可能不用R包,减少依赖变动风险。
方法1: 使用cat()直接输出
cat('<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>', file="output.html")
方法2: 使用writeLines()
html_content <- c('<!DOCTYPE html>','<html>','<head>','<title>My Page</title>','</head>','<body>','<h1>Hello World</h1>','</body>','</html>')
writeLines(html_content, "output.html")
方法3: 使用sink()
sink("output.html")
cat('<!DOCTYPE html>\n')
cat('<html>\n')
cat('<head>\n')
cat('<title>My Page</title>\n')
cat('</head>\n')
cat('<body>\n')
cat('<h1>Hello World</h1>\n')
cat('</body>\n')
cat('</html>\n')
sink()
2. 逐句拼凑html文件
如果不同R文件、同一个R文件的不同位置都要输出信息到同一个html报告文件中呢?
- 使用函数 cat的 append=T参数:
cat('\n</body>\n</html>', file = filepath, append = TRUE)
(1)先定义库函数:
# 初始化HTML文件
init_html <- function(filepath) {writeLines('<!DOCTYPE html>\n<html>\n<head>\n<title>Project Output</title>\n</head>\n<body>', filepath)
}# 添加HTML片段
add_html_section <- function(filepath, content, section_title) {section <- paste0('\n<h2>', section_title, '</h2>\n<div>', content, '</div>')cat(section, file = filepath, append = TRUE)
}# 完成HTML文件
finalize_html <- function(filepath) {cat('\n</body>\n</html>', file = filepath, append = TRUE)
}
逐个写入函数有局限性,需要定义好h2和子内容。
(2)在不同位置写文档:
项目不同位置使用示例
output_file <- "project_output.html"# 位置1:初始化文件
init_html(output_file)# 位置2:数据分析模块
analysis_result <- "<p>数据分析结果...</p>"
add_html_section(output_file, analysis_result, "分析报告")# 位置3:可视化模块
plot_html <- "<img src='plot.png' alt='分析图表'>"
add_html_section(output_file, plot_html, "可视化结果")# 位置4:最终完成
finalize_html(output_file)
3. 自由写html文件,自定义各种标签
如果想更自由的写各种html标签呢?
(1)核心函数
con <- file(outputFile, "w") #打开文件,如果想追加,使用oepn="a"
writeLines(something, con) #写文本
close(con) #关闭文件
(2)包装函数
# functions
html=function(text, tag, fw=con){rs=sprintf("<%s>%s</%s>", tag, text, tag)writeLines(rs, fw)
}
htmlRaw=function(text, fw=con){writeLines(text, fw)
}
# 类似的,可以包装更多函数
h1=function(text){ html(text, "h1")}
h2=function(text){ html(text, "h2")}R2=function(num){round(num, 2)
}now=function(){as.character( format(Sys.time(), '%Y%m%d_%H%M%S') )
}
(3)用法
html("End --", "p")htmlRaw("<div class=box>")
Ref:
- http://blog.dawneve.cc/index.php?k=R&id=0_2#26