Read files and save R objects using file names from tibble

I have a number of .csv files I would like to load in R and then save each as an R object. I could do e.g.:

first <- read_csv(a.csv)
second <- read_csv(b.csv)
third <- read_csv(c.csv)
save(first, file="first.csv")
save(second, file="second.csv")
save(third, file="third.csv")

I already have the file names and the R object names in a tibble and I was wondering how to read the files and save their contents in an object with the corresponding name from the tibble.
This is how the tibble looks like:

> new_tibble(list(file_name = c("a.csv","b.csv","c.csv"), dataset_name=c("first", "second", "third")))
# A tibble: 3 x 2
  file_name dataset_name
  <chr>     <chr>       
1 a.csv     first       
2 b.csv     second      
3 c.csv     third 

I thought this might involve some dplyr transformations and creating a nested dataframe to hold temporary the files, but I don't really know where to start from.

Here is a reproducible example of how you can work with lists of datasets and read them in / save them out.

# list datasets
# note: `list.files` can create a list of all files in a folder for you
data <- list(iris, cars, faithful) # using built in r data sets
names <- list("iris.csv", "cars.csv", "faithful.csv")

# write the files, so we can show how to read them in
mapply(write.csv, data, names) # save the files as csvs

# read the files into R and create a single list of data sets
new_data <- lapply(names, read.csv)

# save as rds - one list object with all three datasets

# save as three separate rds files
# change the file extension
new_names <- sub(".csv", ".rds", names)
mapply(saveRDS, new_data, new_names)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.