Cannot read-in data in my working directory

Hello all,
I've had this super annoying bug for months now I'm just getting around to asking for help with. For some reason I cannot read in my data from my Rmarkdown file by running the individual line of code in the first chunk. It looks like this:

sonadata=read.csv("sonadata.csv",header = TRUE,na.strings = "")

Even with the correct working directory set and running RStudio as administrator still returns this error message when I try to run this line:

cannot open file 'sonadata.csv': No such file or directoryError in file(file, "rt") : cannot open the connection

If I copy and paste the code directly into the console however, it works just fine. It also works if I copy and paste it into a blank, new script. Every time I try to run it from RMarkdown however, it gives me an error.

Is the RMarkdown document in the same directory as the CSV file? RMarkdown uses the directory with the .Rmd file as the working directory, which is not necessarily your ordinary working directory.

1 Like

Ah, it is not. I have my Markdown files stored in a folder of scripts, and my data stored in a separate folder just for my data frames. I open RStudio by double-clicking on the RMarkdown file, and then changing the working directory to that of the folder with the data in it.

So if I put everything in one folder it should work?

Yes, but your way of organizing sounds nice. You can keep it by referencing files with relative file paths.

For example, if your project file tree looks like this:

ā”œ data/
ā”‚   ā”” sonadata.csv
ā”” scripts/
    ā”” report.Rmd

Then code in report.Rmd can reference the data file like this:

sonadata=read.csv("../data/sonadata.csv",header = TRUE,na.strings = "")

The double period (..) in the path means "one directory up", which would be the project-folder directory.

Thanks!! That mostly worked lol. I tried your exact code and it didn't work, but I used it to find the solution:

Went into Windows Explorer and copied as text the exact file path of the folder where my data is, and pasted that in. Had to replace all of the forward slashes with back slashes, but it works now!

sonadata=read.csv("C:/Users/Admin/OneDrive/Research/Floors/SONA pilot/Data Frames/sonadata.csv")

From now on I will just use the whole file path to read in my code.

It would probably be better to use a package like here to deal with such file path issues:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.