CSV and Excel file remain one of amongst the most well-used file formats for exchange data.
#setup where to read the filesetwd("~/Desktop")# en write the filetest <- read.csv(df, "data.csv")
assuming your data is store inside df var, fairly simple:
#setup where to write the filesetwd("~/Desktop")# en write the filewrite.csv(df, "data.csv")
# the file.choose() will prompte a file selector# the 1 say we want to load the first tabtest <- xlsx::read.xlsx(file.choose(),1)
A little bit more complex, we’ll use the ‘xlsx’ package
#setup where to write the filesetwd("~/Desktop")# if the package is not instal yet, run this# install.packages("xlsx")# Loading the packagelibrary(xlsx)# we write the filewrite.xlsx(df, "data.xlsx")
A few more tips for you:
I’ll like to use the sheetName option to explicitly name the tab. The default name is “Sheet1”. Quite useful to have a record of when the file has been generated for example. Replace last instruction what follows and you’ll be able to know.
write.xlsx(df, "data.xlsx", sheetName=format(Sys.Date(), "%d %b %Y"))
Another good one that I like is to send the excel file to a Shared folder directly. Replace first instruction by
Of course, replace the file path with yours.
Aggregate several CSV files into one using file name as a column
library(plyr)library(readr)library(purrr)# add the path where the csv's are locatedsetwd("./Downloads/test/")# list csv files inside the directory# for each: import the csv (read.csv function)# add filename as a column# and mergeTbl <- list.files(path = "./",pattern="*.csv",full.names = T) %>%map_df(function(x) read_csv(x, col_types = cols(.default = "c")) %>%mutate(filename=gsub(".csv","",basename(x))))View(Tbl)