From what I can deduce, latex code below should print R code in a PDF. Note I'm trying to embed code in a .tex file. However its not working - do you know what I'm doing wrong?

\newcommand{\rinline}[1]{SOMETHING WRONG WITH knitr}

this is my text \rinline{1+1}

this is more text \rinline{x} % created object in R: x <- 1:10

I've figured out how to embed R code in a .Rnw file. However, I'm trying to embed code in a .tex file. This link suggests this is possible:

My understanding is that .Rnw files are a 'middle man' between R and latex, and to produce a PDF document, at some point the R code needs to come out of the .Rnw file and into a .tex file. To keep things as simple as possible, I'm trying to embed the R code straight into a .tex file.
Last edited:
Problem is, any changes in the .tex file do not show up in the .Rnw file. So if you re-run knit, any changes in the .tex file get over written. I would be happy to work with purely .Rnw files, but .Rnw files do not open in latex editors such as texstudio.


Ambassador to the humans
My suggestion was mainly so that you could see how to actually embed the R code. You mentioned you knew how to do it directly in the Rnw and wanted to know how to embed R directly in tex so I figured you could just see what the resulting tex file looks like and copy that if you want to write directly in tex.

Are you sure you can't get texstudio to open a Rnw file? I can (on Linux) - you just need to when you choose "Open Files" the box from "Tex files" to "Any files". If that doesn't work you can always just rename the file.Rnw to file.tex

I'm assuming you're just talking about embedding R code itself - not the output. If you want the output then you really should just stick with .Rnw and use knitr.
Yes you're right, texstudio can open .Rnw files by changing options in 'Open Files' box - I missed that. That removes quite a few problems.

So for combining R data analysis with writing reports and articles, would you recommend working purely with .Rnw files? Does working with .Rnw files for producing PDFs introduce any other restrictions at all?


Ambassador to the humans
Not that I can think of. Really a file extension is relatively meaningless and all you're doing is taking a tex file and adding some R code to it with slightly special syntax that gets modified to pure latex after you run knit on it. It's a lot more convenient if you're actually trying to add R code and/or the output of R commands.
Thanks I've learnt a couple of things from this thread.

One thing I have just noticed is syntax highlighting is removed when opening an .Rnw file in an ios app called textastic. Might email app owner regarding that, as I often prefer writing on iPad as opposed to Mac.


Ambassador to the humans
You could always just rename it to have a .tex extension. I think knitr will knit a file ending in .tex as if it were a .Rnw file.