简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM