Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save and Load multiple dataframes from one CSV

Tags:

dataframe

r

csv

How can I save 3 dataframes of different dimensions to one csv in order to load them afterwards in 3 different dataframes?

E.g

write.table(A, file = "di2.csv", row.names = FALSE, col.names = FALSE, sep=',')
write.table(B, file = "di2.csv", row.names = FALSE, col.names = FALSE, sep=',', append=TRUE)
write.table(C, file = "di2.csv", row.names = FALSE, col.names = FALSE, sep=',', append=TRUE)

or in a more elegant way

write.csv(rbind(A, B, C), "di2.csv")

How can I load this CSV to 3 dataframes, A,B and C?

like image 935
Panos Kal. Avatar asked Sep 10 '26 02:09

Panos Kal.


2 Answers

This worked for me:

save(A_table, B_table, C_table, file="temp.Rdata") 
load("temp.Rdata")
like image 70
Panos Kal. Avatar answered Sep 11 '26 18:09

Panos Kal.


As mentioned in the comments if your purpose is just to read them back into R later then you could use save/load.

Another simple solution is dump/source:

A <- B <- C <- BOD # test input
dump(c("A", "B", "C"))

# read back
source("dumpdata.R")

Other multiple object formats that you could consider would be hdf and an SQLite database (which is a single file).

On the other hand if it is important that it be readable text, directly readable by Excel and at least somewhat similar to a csv file then write the data frames out one after another with a blank line after each. Then to read them back later, read the file and separate the input at the blank lines. st and en are the starting and ending line numbers of the chunks in Lines.

A <- B <- C <- BOD # test inputs

# write data frames to a single file
con <- file("out.csv", "w")
for(el in list(A, B, C)) {
   write.csv(el, con, row.names = FALSE)
   writeLines("", con)
}
close(con)

# read data.frames from file into a list L
Lines <- readLines("out.csv")
en <- which(Lines == "")
st <- c(1, head(en, -1))
L <- Map(function(st, en) read.csv(text = Lines[st:en]), st, en)

Note that there are some similarities between this question and Importing from CSV from a specified range of values

like image 35
G. Grothendieck Avatar answered Sep 11 '26 20:09

G. Grothendieck