The past few years, I have been searching regularly for ways of formatting R code on +Blogger. Although different possibilities were available, almost always I ended up using the online Pretty R syntax highlighter by copying parts of a script and pasting these in blog posts after highlighting.
Luckily I found a workaround, which I’m outlining below, for my own future reference! 🙂
Create your R script
As an example, I’m using my last post on variography with gstat and ggplot2. You can compile the notebook into a self-contained HTML document, but the images are then included as Base64 code, and do not get picked up when sharing the post url on e.g. social networks. Therefore, I chose not to have the HTML self-contained at this point, which means the images have to be uploaded to Blogger at some point, or hosted somewhere else with modifications of the image urls in the html code. The original script can be found here.
Compile your notebook
Once your script is complete, press the “Compile Notebook” button, or use Ctrl+Shift+K to compile your script to an RStudio notebook. Once the RStudio HTML preview pops up, check if everything is there.
Get self-contained html body code (without images)
Now select the contents of the preview, copy it, and paste it into the Blogger Compose editor. Everything should look exactly as in the RStudio HTML preview, except for the images, which should not be there at this point.
Modify image urls
For inserting the images, switch to the HTML editor, and search for the “img” HTML tags. Then modify the src attributes, so they point to the urls of the images (you can host them wherever you want, but I’m using Google Drive). Another way of doing this is to upload the images in the Compose editor, and insert them in the correct place within the notebook.
Further modify HTML if necessary
Now save and preview your post. Are things still looking as expected? Then you can probably skip this step. If some weird things happened to your notebook, you might want to check for incompatibilities with your blog CSS code. In my case, I had to set border-left to 0px for the code blocks, as my blog CSS uses a border there. This was quickly solved by doing a find and replace for which I used this R function on a text file with HTML code:
library(rtoolz) find_and_replace('html.txt','style="','style="border-left: 0px;')
After modifying the HTML code, insert it again in the Blogger HTML editor.
Any people out there doing similar things? Please let me know!