How to enable Google Analytics on the GitHub page generated by RMarkdown?

How can I always include a Google Analytics passcode in my GitHub Pages generated by R Markdown?

I am currently creating a webpage hosted on GitHub pages using RMarkdown. To create a site, I run rmarkdown::render_site() . This command combines all R Markdown documents to create the corresponding .html files.

However, I want to enable Google Analytics on my site. To do this, I need to include the University Analytics tracking code in my property by inserting JavaScript code into 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 reinserts the index.Rmd file and thus overwrites the index.html file, including the Google Analytics code that I entered directly earlier.

How can I fix this problem and always have my Google Analytics code contained on the page?

+5
source share
1 answer

I just figured out how to do this while trying to add google analytics to my own RMD site on Github pages.

To add the Google Analytics code before the closing </head> html document created using RMD ...

Step 1: Create an .html file containing Google Analytics Script and save it in the working directory of your site. (Just create a new text file, paste Script, save the file filename.html.

Step 2: Adjust the yaml header of your rmd file to include the arguments include: and in_header:, as well as a link to the .html file containing the tracking code

 --- title: "" output: html_document: includes: in_header: GA_Script.html --- 

Step 3: Adjust the yaml headers for each rmd file associated with your site so that each page returns to Google Analytics.

It is recommended that the Google Analytics tracking code appear before the closing <\head> on html sites. The above method will do this.

If for some reason you want to include it in the body of the html code, you can simply include the GA code in the body of the rmd file by inserting it between the html_preserve command:

 <!--html_preserve--> Google Analytics Code Here <!--/html_preserve--> 
+4
source

Source: https://habr.com/ru/post/1262020/


All Articles