knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
library(fgeo.base)
library(fgeo.tool)
library(fs)
library(purrr)
library(readr)
library(writexl)

If you have multiple files in a directory, you may want to combine them all into a single dataframe and export it as a .csv or excel file. Here is how you can do this and a a little more.

Suppose you have these files in a directory:

files <- fgeo.x::example_path("files")
dir(files)

Let's read all the .csv files into a single dataframe.

combined <- csv_to_df(files)
combined

You can then write a .csv file.

write_csv(combined, "combined.csv")

An alternative is to read each file into an individual dataframe and store all dataframes into a list.

dfs <- xl_to_dfs(files)
dfs

This intermediate step is useful if you want to identify the source of each dataframe.

id <- name_dfs(dfs, name = "source")
id

You can then reduce the structure of these data by row-binding each dataframe of the list into a single dataframe.

combined_id <- reduce(id, rbind)
combined_id

Now you can save this dataframe to a .csv file exactly as you did before.

write_csv(combined_id, "combined_id.csv")

Instead of a .csv you may write an excel file of the combined dataframe.

write_xlsx(combined_id, "combined_id.xlsx")

Or you may map each dataframe of the list to an individual sheet of a single excel workbook.

write_xlsx(id, "combined_id.xlsx")

If later you need to read multiple excel files you may use the same approach you used to read .csv files with the functions xl_to_dfs() and xl_to_df(). For more details see ?files_to_df.

Reading data safely

Acknowledgment

Thanks to Jessica Shue for inspiring the code and workflow shown here.



forestgeo/fgeo.tool documentation built on Sept. 11, 2022, 1:44 a.m.