Skip to course content
Free R data course

R Foundations for Data Analysis

Unit 01.05: Outputs are rebuilt, never edited

If a file in your outputs folder cannot be deleted without anxiety, it is not really an output.

Outputs are rebuilt, never edited

The test for whether your project is reproducible is blunt: delete everything the code produced, run the script, and see whether you get it back. Anything that does not come back was made by hand, and the record of how is in your memory.

That means charts are saved by code, not exported from a preview pane, and tables are written by code, not copied into a spreadsheet and tidied. It feels slower for the first chart and much faster by the fifth, because changing the data means re-running rather than redoing.

Where the files go matters less than the fact that a single folder holds everything generated, so 'delete and rebuild' is one command.

This block writes both a table and a chart from code.


# Outputs are rebuilt by the script, so they can always be deleted.
suppressPackageStartupMessages({library(dplyr); library(readr); library(ggplot2)})

outputs <- file.path(tempdir(), "outputs")
unlink(outputs, recursive = TRUE)
dir.create(outputs)

visits <- data.frame(ward = c("North", "South", "East", "West"),
                     count = c(412, 388, 502, 331))
summary_table <- visits |> arrange(desc(count))

write_csv(summary_table, file.path(outputs, "ward-visits.csv"))

chart <- ggplot(visits, aes(x = reorder(ward, count), y = count)) +
  geom_col() +
  labs(x = "Ward", y = "Visits", title = "Visits by ward")
ggsave(file.path(outputs, "ward-visits.png"), chart,
       width = 5, height = 3, dpi = 150)

info <- file.info(list.files(outputs, full.names = TRUE))
for (i in seq_len(nrow(info))) {
  cat(sprintf("%-18s %6d bytes\n", basename(rownames(info)[i]), info$size[i]))
}
cat("\nBoth files are reproducible; neither is edited by hand.\n")

The CSV lands at 49 bytes and the PNG at 16418 bytes. The exact sizes are not the point — the point is that both were produced by lines you can read, so a change to the data changes both files with no further work, and neither can drift out of step with the analysis that made it.

The mistake this prevents

The mistake is exporting the chart by hand 'just for now'. The data is revised, the table is regenerated, the chart is not, and a report goes out with a figure and a picture that disagree.

Takeaway

Write every output from code into one generated folder. If you cannot delete that folder and rebuild it with one run of the script, find out why before the project grows.