reading in multiple files at once in R Markdown

Hi all, I'm trying to find a way to import multiple files at once into R and I've found this nice little script that works well. Only, there's an odd problem: it works perfectly when I run it in a normal script file, but when I put it into an R Markdown code chunk, it doesn't return anything. Not sure why; any help would be appreciated

Code is here:

file_path <- "JLWOP/Data and Models/"

# view all files
file_path %>% list.files()

# save only file names with the desired extension
csv_file_names=file_path %>% 
  list.files() %>% 
  .[str_detect(., ".csv")]


# Load everything into the Global Environment
csv_file_names %>%
  purrr::map(function(file_name){ # iterate through each file name
    assign(x = str_remove(file_name, ".csv"), # Remove file extension ".csv"
           value = read_csv(paste0(file_path, file_name)),
           envir = .GlobalEnv)
  })

When I run this in an R script, both of my .csv files load in perfectly. When I run it in an R Markdown, all I see is the return

list()

In the Markdown document

You coud try the here package. If I'm not mistaken, RMarkdown searches the paths from the directory where the rmd is located.

https://cran.r-project.org/web/packages/here/vignettes/rmarkdown.html

If you define:

file_path <- here::here("JLWOP", "Data and Models")

it might work :slight_smile:

Thanks! Though I tried it with {here} originally and couldn't get these lines to work at all :frowning:
The second to last line, value=read_csv(paste0(file_path, file_name)) doesn't include the / needed if I use here; it just smushes the name and path together

Suppose I could modify that line to fix that but I'm not sure how

the function file.path() should be used rather than paste0() for such purposes as it knows what the ideal symbol separator for the Operating System is and it will put that in between

1 Like

That fixed it! Thank you!

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.