How to open next folder in working directory for only one file?

814 views Asked by At

I have a working directory

setwd("C:/User/WorkDirectory")

I have files in the working directory

"File 1.csv", "File 2.csv", "File 3.csv", "Folder 1"

I have no problem accessing the 3 files

df1<-read.csv("File 1.csv",check.names=FALSE)

However i would like to open the file in the folder Folder 1 while maintaining my working directory as it is.

I tried something like this

read.csv(paste0(setwd("./Folder 1/"),"File Another 1.csv"))

Is there a nice and elegant way of doing this. There is a reason I'm trying to do this as this folder contains a sub section of files.

2

There are 2 answers

0
akrun On BEST ANSWER

Use file.path - setwd is for setting the directory, whereas getwd returns the path of working directory.

setwd("C:/User/WorkDirectory")
read.csv(file.path(getwd(), "Folder 1", "Another 1.csv"))

Or we may also use . to signify the working directory

read.csv(file.path(".", "Folder 1", "Another 1.csv"))
0
M-- On

I am not completely clear on your intent, but I guess a recursive list.files can be helpful here;

setwd("C:/User/WorkDirectory")
temp <- list.files(pattern = "*.csv", recursive = T)

This lists the CSV files within WorkDirectory and its sub-folders. You can loop through the listed files and read them into your environment;

my_csv_files <- lapply(temp, read.csv)

or if you want them as multiple dataframes saved to your environment and not as a list of dataframes like above:

list2env(
  lapply(setNames(temp, make.names(gsub(".*/([^.]+).*", "\\1", temp))), 
         read.csv), envir = .GlobalEnv)