Sweave, R, Beamer: How to convert LaTex text to Rnw file in R comments?

Say I have a .Rnw file containing a regular LaTex mixed with fragments of R code. (I am particularly interested in converting a .Rnw slide .Rnw , but this question applies to any .Rnw document). Now I want to convert this to a file containing all the R code, plus all the text that is usually generated by LaTex, as R comments. In other words, the functionality I want is similar to what Stangle() does, but I also I want the entire text part of LaTex to be converted to plain text, which is commented out in the resulting .R file.

This will be a very convenient way to automatically generate a commented R file, which can be easily found in your favorite syntax-highlighting editor (e.g. emacs). It might seem like a great idea for a Sweave document that a long article with a bit of R code, but it starts to look attractive when the .Rnw document is actually a presentation of slides (for example, using beamer ) - the text part of the slides will make great comments for code R.

Anyone have any ideas on how to do this? Thanks in advance.

+7
source share
1 answer

Here is one approach using regex . Some problems remain and I will keep a list that will be updated with permissions.

 # READ LINES FROM RNW FILE lines <- readLines('http://users.stat.umn.edu/~charlie/Sweave/foo.Rnw') # DETECT CODE LINES USING SWEAVE CHUNK DEFINITIONS start_chunk <- grep("^<<.*=$", lines) end_chunk <- grep("^@" , lines) r_lines <- unlist(mapply(seq, start_chunk + 1, end_chunk - 1)) # COMMENT OUT NON CODE LINES AND WRITE TO FILE lines[-r_lines] <- paste("##", lines[-r_lines]) writeLines(lines, con='codefile.R') 

QUESTIONS REMAINING:

  • Doesn't work with chunks inside other chunks using <<chunk_name>>
+8
source

All Articles