Data Import/Export
Read and write CSV, TSV, RDS, RData, and text files with base R.
Code
# CSV
df <- data.frame(id = 1:3, name = c("A", "B", "C"), value = c(10, 20, 30))
write.csv(df, "data.csv", row.names = FALSE)
read_back <- read.csv("data.csv")
print(read_back)
# TSV
write.table(df, "data.tsv", sep = "\t", row.names = FALSE, quote = FALSE)
print(read.delim("data.tsv"))
# RDS - single R object
saveRDS(df, "data.rds")
restored <- readRDS("data.rds")
print(restored)
# RData - multiple objects
x <- 1:5
y <- letters[1:5]
save(x, y, file = "vars.RData")
rm(x, y)
load("vars.RData")
print(x); print(y)
# Excel via readxl (if installed)
# library(readxl)
# sheets <- excel_sheets("file.xlsx")
# tbl <- read_excel("file.xlsx", sheet = 1)
# JSON via jsonlite (if installed)
# library(jsonlite)
# json <- toJSON(df)
# parsed <- fromJSON(json)
# Lines
writeLines(c("first", "second", "third"), "lines.txt")
print(readLines("lines.txt"))
# Capture output for reproducible logs
report <- capture.output(print(summary(df)))
writeLines(report, "summary.txt")Explanation
read.csv and write.csv cover tabular text I/O, with read.delim handling arbitrary delimiters. saveRDS preserves a single R object with full type fidelity, while save/load round-trip several objects at once. For Excel, JSON, and other formats, lightweight packages like readxl and jsonlite plug into the same data frame interface.
More R Snippets
Data Frames
Create, inspect, filter, mutate, sort, aggregate, and merge data frames.
Vectors
Build atomic vectors, apply vectorized ops, index, and recycle.
ggplot2
Build layered plots with geoms, facets, and themes using the grammar of graphics.
dplyr
Chain mutate, filter, group_by, summarise, and joins with the native pipe.
Statistics
Compute summaries, run t-tests, linear models, ANOVA, and use distributions.
Apply Family
Apply functions over arrays, lists, and groups with apply, lapply, sapply, tapply.