R sink to .csv with predefined width

98 views Asked by At

I've got an R script that exports a data frame and some other lines to .csv file using sink. Another script collects the data from multiple csv's exported in this way.

These scripts need to be used by multiple users, and while the process works fine for me, it has introduced errors when I asked someone else to run it.

The reason seems to be that the sink function apparently exports the data frame at the width of the console window in RStudio, so in the event that the width of the data frame is too wide, it wraps it over multiple lines in exactly the same way that printing to the console window would. Consequently, the second script isn't locating the data it is looking for.

Is it possible to ensure that the output to .csv disregards the display window width and makes the file wide enough to store all columns, regardless of who the user is or what settings they have on RStudio or elsewhere?

Edit: here is some example code that reproduces the problem:

my.df <- data.frame(a = c(1:10), 
       b = c(1:10),
       c = c(1:10),
       d = c(1:10), 
       e = c(1:10), 
       f = c(1:10), 
       g = c(1:10), 
       h = c(1:10), 
       i = c(1:10), 
       j = c(1:10))
sink(file = "test.txt")
print("title information")
print(my.df)
cat("\n")
print("... some other lines...")
sink(file = NULL)

Running this code 1) with a wide screen layout, and 2) with a narrower screen screen layout, produces different output in the text file.

2

There are 2 answers

0
Phenomniverse On BEST ANSWER

For other interested parties, the width can be set by using the line:

options(width=400)

before using the sink() command.

2
Roland On

sink is not designed for creating reports. As I suggested in a comment, use knitr. Here is how you do that with RStudio:

Step 1. Create an R Notebook file.

Step 2. The file content should look like this (customize as needed, e.g., by setting a width for the output):

---
title: "title information"
output:
  html_document:
    df_print: paged
    code_download: true
---
```{r, echo = FALSE, comment = ""}
my.df <- data.frame(a = c(1:10), 
       b = c(1:10),
       c = c(1:10),
       d = c(1:10), 
       e = c(1:10), 
       f = c(1:10), 
       g = c(1:10), 
       h = c(1:10), 
       i = c(1:10), 
       j = c(1:10))
```
```{r, echo = FALSE, comment = "", purl=FALSE}
print(my.df)
```

... some other lines...

Step 3. Knit the file. This will create an HTML file that your clients can view in their internet browser. We have embedded the Markdown code, i.e., there is a download button when you view the HTML file.

Step 4. You can recover the code creating the data.frame with knitr::purl("test.Rmd", documentation = 0). You may want to use dput in your markdown file.

I recommend the R Markdown Cookbook: https://bookdown.org/yihui/rmarkdown-cookbook/