Skip to content
R

Data Import/Export

Read and write CSV, TSV, RDS, RData, and text files with base R.

By EZ4Code Team
iocsvimport

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