E.g., If I had a file called test.html, I tried:

pandoc -s -S --toc test.html -o test-toc.html


Thus, it makes this html file look like this one. I'd like to preserve the formatting.

I'm not sure how you can tell Pandoc to keep all the style and header information. However, presumably this style does not change very much, so why don't you copy this into a .css stylesheet file and point to this file when generating the output HTML (with the -c or --css command line options)? You can tell Pandoc to embed this stylesheet information into your final output using the --self-contained command line option (see here for the full list of options).

For the MathJax script in your input HTML file you can use

--mathjax=https://c328740.ssl.cf1.rackcdn.com/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML


Finally, for the R syntax highlighter you can use

--include-in-header=r_syntax.html


where r_syntax.html contains the appropriate JavaScript wrapped in <script> tags.

Update: Having said all that, you can include all the style and script information in a single file (say r_styling.html) and include this at the end of the header of your output HTML using

pandoc -s -S --toc -h r_styling.html --self-contained test.html -o test-toc.html


The -h option is shorthand for --include-in-header.