library(pacman)
::p_load(fs, folderfun, tidyverse) pacman
Reading files easily
Reading and writing files can sometimes be challenging. This is an attempt to share the process I am following for making it easy to reading and writing of files in R.
Reading required packages.
Define the path wherein the input and output will be located in the local drive.
I have found the package folder function package and fs package to be very useful for file managing files.
- fs::path() will be used to construct the path of the location folder
- folderfun::setff() will be used to define a new function, wherein the first argument is the name of the new function prceded by ff.
# Defining the input function
::setff(name = 'In',
folderfun::path("C:/Users/aqureshi037/PycharmProjects/Ahsan_Blog_Quarto",
fs"posts", "file_n_folder_Mgmt", "input_data")
)
Created folder function ffIn(): C:/Users/aqureshi037/PycharmProjects/Ahsan_Blog_Quarto/posts/file_n_folder_Mgmt/input_data
# Defining the ourput function
::setff(name = 'Out',
folderfun::path("C:/Users/aqureshi037/PycharmProjects/Ahsan_Blog_Quarto",
fs"posts", "file_n_folder_Mgmt", "output_data")
)
Created folder function ffOut(): C:/Users/aqureshi037/PycharmProjects/Ahsan_Blog_Quarto/posts/file_n_folder_Mgmt/output_data
Reading of the file
iris.csv file is already located in the ‘input’ folder.
data(iris)
#Writing the data to the folder
::write_csv(iris, ffOut("iris.csv"))
readr
#Reading the data from the folder
<- readr::read_csv(ffIn("iris.csv")) iris_data
Rows: 150 Columns: 5
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (1): Species
dbl (4): Sepal.Length, Sepal.Width, Petal.Length, Petal.Width
ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.