Pragyaditya Das Pragyaditya Das - 2 months ago 6
R Question

To write the output of a function into a pdf file

I have written the following function,

CSVDimension <- function(.csv) {
csv <- read.csv(.csv)
dimValue <- dim(csv)
print("The dimension of the dataset is:")
headValue <- head(csv)
print("The head of the dataset is:")
return(list(dimValue,headValue))
}


This function prints the dimension of a given dataset when we run,

> CSVDimension("path/to/file/dataset.csv")


My next step is to print this result on to a properly-formatted pdf file.

How can I do that?

Thanks.

Answer

Assuming you have pandoc installed (and in your path), you can modify your function to

    CSVDimension <- function(.csv, .pdf) {
      csv <- read.csv(.csv)
      dimValue <- dim(csv)
      msg <- paste("The dimension of the dataset is:", paste(dimValue, collapse = " : "))
      print(msg)
      md <- sub("\\.pdf", ".md", .pdf)
      cat(msg, file = md)
      system(paste("pandoc -o", .pdf, md))
      return(dimValue)
}

where .csv is the path to your csv file, and .pdf the path to the resulting pdf output.

Comments