Yu Na
Yu Na

Reputation: 122

How can I set the working directory to a subfolder?

I am using R to try to read all the .xlsx files in a subfolder within a main folder. The code seems intuitive, but I am stumbling into a roadblock with the working directory.

My relevant code:

setwd("~/Downloads/Job Postings")

for (dir in list.dirs()[-1]) {
  setwd(dir)

  files <- list.files(pattern="*.xlsx")

  require(purrr)
  main_dF <- files %>% map_dfr(read.xlsx)
}

The code seems intuitive, but I receive error Error in setwd(dir) : cannot change working directory. How can I adjust the setwd() command? Thanks

Upvotes: 1

Views: 575

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24790

I think you have two issues.

  1. You change directory into a sub directory in the loop, but never return
  2. You assign the result to main_df, but that won't ever be accumulated across the subdirectories

You might try something list this.

setwd("~/Downloads/Job Postings")
results <- list()
for (dir in list.dirs()[-1]) {
  setwd(dir)

  files <- list.files(pattern="*.xlsx")
  require(purrr)
  main_dF <- files %>% map_dfr(read.xlsx)
  results[[dir]] <- main_df
  setwd("~/Downloads/Job Postings")
}
finalresult <- bind_rows(results)

Upvotes: 1

Related Questions