'How can I save different tables into one csv on the same tab above each other?
Solution 1:[1]
Put your 4 data frames into a named list L such as the test data shown below based on the built-in BOD data frame.
As in the question, we assume that the sum of the number of columns in the first two data frames equals the sum of the number of columns in the last two data frames.
Define a fmt function which inputs a name from the list L and outputs a character ts series with the name at top. We use ts series because those allow cbind to be used with arguments having different numbers of rows. Finally use write.table to output the result. We just output it to the console but you can modify the write.table statement appropriately to output to a file.
No packages are used.
# test data
b <- BOD; rownames(b) <- letters[1:nrow(BOD)]
L <- list(d1 = b[1:2, ], d2 = b[1:3, ], d3 = b[1:4, ], d4 = b[1:5,])
fmt <- function(nm, DF = L[[nm]]) {
m <- cbind(rownames(DF), sapply(DF, as.character))
as.ts(rbind(c(nm, rep("", ncol(DF))), colnames(m), m))
}
m1 <- cbind(fmt("d1"), "", fmt("d2"))
m2 <- cbind(fmt("d3"), "", fmt("d4"))
m <- rbind(m1, "", m2)
write.table(m, sep = ",", na = "",
row.names = FALSE, col.names = FALSE, quote = FALSE)
giving:
d1,,,,d2,,
,Time,demand,,,Time,demand
a,1,8.3,,a,1,8.3
b,2,10.3,,b,2,10.3
,,,,c,3,19
,,,,,,
d3,,,,d4,,
,Time,demand,,,Time,demand
a,1,8.3,,a,1,8.3
b,2,10.3,,b,2,10.3
c,3,19,,c,3,19
d,4,16,,d,4,16
,,,,e,5,15.6
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

