I am trying to learn how to:
- Import all files (of a certain type) from the working directory and name them accordingly
- Export all files from R to the working directory and name them accordingly
1) Importing
Suppose I have these files (of a certain type) on my working directory with different names(my_file.csv, my_r_file.csv, my_file.RDS, my_r_file.RDS etc.). The function below can list all of their names:
temp_RDS = list.files(pattern="*.RDS")
temp_CSV = list.files(pattern="*.csv")
But from here, I don't know how to bulk import them and name them accordingly (using an index). For example:
#automate
file_1 = read.csv("my_file.csv")
file_2 = read.csv("my_r_file.csv")
file_1 = read.csv("my_file.RDS")
file_2 = read.csv("my_r_file.RDS")
2) Exporting
Suppose I have these files in R with different names - I would like to save all these files as csv files into the working directory. Suppose I have these files in R:
monday = data.frame(name = "john", day = "monday")
october = data.frame(name = "sara", month = "october")
# etc
I found this code that might be able to export (8) files provided they all start with "df" - but this will not work if all the files are named differently:
dat <- do.call(rbind, lapply(1:8, function(x)get(paste0("df", x))))
#CSV Option
for(i in 1:ncol(dat)) write.csv(dat[,i], paste0("file_",i, ".csv"), row.names=F)
#RDS option
for(i in 1:ncol(dat)) saveRDS(dat[,i], paste0("file_",i, ".RDS"), row.names=F)
- Are there more direct/efficient ways to bulk import/export files from/to R?
Thank you!