export all the content of r script into pdf

Viewed 94348

I would want to export all the content of r script into pdf. Could it be possible? I used these commands export, but what I see I just exported graphics

pdf(file = "example.pdf")
  dev.off()

Thank you!

    setwd("C:/Users/Prat/Desktop/c")
    > dir()
    [1] "script.R"
    > knitr::stitch('script.r')
 output file: script.tex

In my folder doesn't appears a script.pdf else a script.tex and a folder with the pictures in pdf enter image description here

4 Answers

You can generate html file by using,

    knitr::stitch_rhtml('filename.r')

As .tex file is not easily readable but html files can view in any browser easily.

Please use the below set of codes (you need to modify it according to your dataset/data-frame name).

library(gridExtra)
library(datasets)
setwd("D:\\Downloads\\R Work\\")
data("mtcars") # Write your dataframe name that you want to print in pdf
pdf("data_in_pdf.pdf", height = 11, width = 8.5)
grid.table(mtcars)
dev.off()

Thanks.

For everyone who is looking for an easy and fast solution, I would propose using the function capture.output (https://www.rdocumentation.org/packages/utils/versions/3.6.2/topics/capture.output) from utils.

One only needs to 1.) capture what ever command one wants to run and assign it to a variable and 2.) then print that variable. Images can be printed along the way as you can see. The example on the webpage I linked above does not use markdown.

Here my example with markdown (this is really all one needs):

```{r, echo = F}
# fake data-set
x = rnorm(50, mean = 3.3, sd=1)
y = rnorm(50, mean = 3.1, sd=0.9)
z = rnorm(50, mean = 3.2, sd=1.1)
# create dataframe
df <- data.frame(x, y, z)

# adding a graphic
plot(df$x, df$y)

# create a model as example
linearMod <- lm(y ~ x + z, data=df) 

# all one needs to capture the output!!:
bla <- capture.output(summary(linearMod))
print(bla)
```

Remark: if one also wants to print the command, that is also easy. Just replace "echo = F" with "warning = F" or remove the text altogether if you also wanna have the warnings printed, in case there are any.

this is the pdf file one gets

Related