Files and Reproducibility
CSV I/O
Write and Read a Table
R scripts often exchange data through CSV files. A script can write a table, read it back, and clean up.
Program
Play the script to watch a temporary CSV become data and then a total.
csv_io.R
Replay: real traced execution (multi-file project)
path <- tempfile(fileext = ".csv")
write.csv(data.frame(x = c(1, 2)), path, row.names = FALSE)
data <- read.csv(path)
total <- sum(data$x)
unlink(path)
cat(total, "\n", sep = "")
path ← /tmp/file.csv
1path <- tempfile(fileext = ".csv")2write.csv(data.frame(x = c(1, 2)), path, row.names = FALSE)values this step/tmp/file.csvpathfile ← 2 rows x 1 col
1path <- tempfile(fileext = ".csv")2write.csv(data.frame(x = c(1, 2)), path, row.names = FALSE)3data <- read.csv(path)values this step2 rows x 1 colfile/tmp/file.csvpathdata ← 2 rows x 1 col
2write.csv(data.frame(x = c(1, 2)), path, row.names = FALSE)3data <- read.csv(path)4total <- sum(data$x)values this step2 rows x 1 coldata/tmp/file.csvpathtotal ← 3
3data <- read.csv(path)4total <- sum(data$x)5unlink(path)values this step3total1, 2data$xfile ← removed
4total <- sum(data$x)5unlink(path)6cat(total, "\n", sep = "")values this stepremovedfile/tmp/file.csvpathcat(total, " ", sep = "")
5unlink(path)6cat(total, "\n", sep = "")output3values this step3total
tempfile
`tempfile` creates a path for short-lived data.
write.csv
`write.csv` writes a data frame to a CSV file.
read.csv
`read.csv` loads a CSV file into a data frame.