简体   繁体   中英

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

Say I have a .Rnw file containing the usual LaTex mixed in with R code chunks. (I'm especially interested in converting a .Rnw slides document, but this question applies to any .Rnw document). Now I want to convert this to a file which contains all of the R code, plus all of the text that would normally be generated by LaTex, as R comments . In other words, the functionality I want is similar to what Stangle() does, but I also want all the text part of the LaTex converted to plain text that's commented out in the resulting .R file.

This would be a very convenient way to automatically generate a commented R file that's easy to look at in your favorite syntax-highlighting editor (eg emacs). This might not sound like a great idea for an Sweave document that's a long article with only a bit of R code, but it starts to look appealing when the .Rnw document is actually a slide presentation (eg using beamer ) -- then the text portion of the slides would make perfect comments for the R code.

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

Here is one approach using regex . There are still some issues that remain, and I will maintain a list which will be updated with resolutions.

# 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')

ISSUES REMAINING:

  1. Does not deal well with chunks called inside other chunks using <<chunk_name>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM