问题
How can I always include the Google Analytics tacking code on my GitHub Pages webpage generated with R Markdown?
I am currently creating a webpage hosted on GitHub Pages using RMarkdown. To create site, I run rmarkdown::render_site()
. This command will knit all R Markdown documents to create the relevant .html
files.
However, I want to include Google Analytics on my site. To do this, I need to include a University Analytics tracking code to my property by pasting the JavaScript code in my main index.html
file. I can easily do this by editing the index.html
file directly. However, every time I run rmarkdown::render_site()
, to render the site, it re-knits the index.Rmd
file, and thus overwrites the index.html
file, including the Google Analytics code I previously entered directly.
How can I fix this problem and always have my Google Analytics code contained in the page?
回答1:
I just figured out how to get this done while trying to add google analytics to my own RMD site on Github Pages.
To add Google Analytics code before the closing </head>
tag of an html document produced from RMD...
Step 1: Create a .html file containing the Google Analytics Script, and save it in the working directory for your site. (Simply, create new text file, paste script, save "filename.html".
Step 2: Adjust the yaml header of your rmd file to contain the includes: & in_header: arguments, and reference the .html file containing the tracking code
---
title: ""
output:
html_document:
includes:
in_header: GA_Script.html
---
Step 3: Adjust yaml headers for each rmd file related to your site so that each page reports back to Google Analytics.
It is recommended that the Google Analytics tracking code be placed before the closing <\head>
tag in the sites html. The method above will get that done.
If for some reason you want to include it in the body of the html code, you could just include the GA code in the body of the rmd file by pasting it in between an html_preserve command:
<!--html_preserve-->
Google Analytics Code Here
<!--/html_preserve-->
回答2:
I manually write the header in the same RMarkdown file and simply include the Google Analytics chunk. This header goes immediately after the yaml. Works like a charm.
---
title: "XXXXXXXXXX"
author: "XXXXXXXXXXX"
date: "`r Sys.Date()`"
---
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=XXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'XXXXXXXXXX');
</script>
</head>
来源:https://stackoverflow.com/questions/41376989/how-to-include-google-analytics-in-an-rmarkdown-generated-github-page