(QuickTip) Writing data frames or lists of data frames to files elegantly
I produce a lot of data frames in my R code, and sometimes need to save them as TSVs for logs, etc. The following function and its input neatly names the output files and saves them, in a properly vectorised manner.
# Define function to write the dfs out
writeFile <- function(dataFrame, dfName) {
fileName <- paste0(dfName, '.tsv')
write.table(dataFrame,
file = fileName,
quote = FALSE,
sep = "\t",
col.names = TRUE,
row.names = FALSE)
}
# Create a list of data frames, where each df in the list is named
dfList <- list(df1, df2, df3)
names(dfList) <- c('df1', 'df2', 'df3')
# Do the thing!
mapply(FUN = writeFile, dataFrame = dfList, dfName = names(dfList))
Explanation
The function writeFile() takes a data frame and a name.
It tacks “.tsv” to the end of the name, and spits the data frame out to the file.
This function can be run manually on a single data frame, but sometimes it’s necessary to do this on multiple.
As is best practice in R, I avoid using for loops and use vectorisation.
Staging multiple data frames to run on this function is done by putting them into a list.
The list is then named.
mapply() runs through the list, appropriately putting the dataFrame and dfName parameters in the right place for the writeFile() function.