更靈活的書寫方式,可以直接看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