Skip to content

Instantly share code, notes, and snippets.

@florisvanvugt
Last active April 16, 2018 20:50
Show Gist options
  • Save florisvanvugt/2c8a4e08e8ed39755d8ebe740da6f8cf to your computer and use it in GitHub Desktop.
Save florisvanvugt/2c8a4e08e8ed39755d8ebe740da6f8cf to your computer and use it in GitHub Desktop.
Convert Rnw (Sweave) to R Markdown (Rmd)
#
# A very cheap-and-cheerful way to convert Rnw (Latex-R-Sweave) into Rmd (R Markdown).
#
# Probably doesn't work with any generality but may be nice to try anyway.
# NOTE: You'll have to do a whole bunch of manual tweaking of the file afterwards,
# because the Rmd will still contain lots of LATEX code.
from tkinter import filedialog
from tkinter import *
import os
import re
root = Tk()
fname = filedialog.askopenfilename(initialdir = ".",title = "Select file",
filetypes = (("R Sweave","*.Rnw"),("all files","*.*")))
if not fname or fname=="": exit
sourcef = fname
targetf = sourcef.replace('.Rnw','.Rmd')
assert targetf!=sourcef
assert not os.path.exists(targetf)
with open(sourcef,'r') as f:
source = f.read()
res = re.findall(r'<<([^<>]*)>>=([^@]+)@',source)
rmd = re.sub(r'<<([^<>]*)>>=([^@]+)@',r'```{r \1}\2\n```\n',source)
with open(targetf,'w') as f:
f.write(rmd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment