R File I/O
There are distinct functions for reading or writing data files.
Contents
Native R
> df <- readRDS("data.rds")
> saveRDS(df, "data.rds")Note that these functions are capable of reading/writing any R object to a file. As such, there cannot be a known type for the return value of readRDS.
Also note that the readr library provides wrappers around these functions named read_rds and write_rds. These are provided solely for naming consistency.
Text
The builtin functions read.csv, read.delim, and read.table can be used to read a text file as data. However, these functions are slower than the equivalents available from the readr library.
Delimiter |
Ingress Example |
Outgress Example |
Comma |
read_csv("data.csv") |
write_csv(df, "data.csv") |
Tab |
read_tsv("data.tsv") |
write_tsv(df, "data.tsv") |
Any character |
read_delim("data.txt", delim="|") |
write_delim(df, "data.txt", delim="|") |
For fixed width data, try:
> df <- read_fwf("data.txt", fwf_widths(c(2,2,NA)))
Stata
The haven library supports Stata versions 8-15.
> df <- read_dta("data.dta")
> write_dta(df, "data.dta")Labels are frequently a problem for moving between Stata and R data formats, as the former does not support labels on decimal values. Use zap_labels, also provided by haven, to remove the offending value labels.
> df$foo <- zap_labels(df$foo)
