"../" relative path directory not working R - r

I often have to work with shared data/code from Dropbox, and all of the files are usually loaded in as df <- import("../data/branch/file_name.csv")
However, this never loads on my computer, so I always have to type in my full directory as df <- import("C:/Users/Name/Dropbox/Folder1/Folder2/data/branch/file_name.csv")
Which makes it difficult for others to reproduce the code. Is there any way to fix this so that R can read the "../" part properly? I always get this error: Error: path does not exist: ../data/branch/file_name.csv
(I used the import function as an example but this problem occurs with other packages or loading functions as well)
I've also tried using "~/" but the problem persists. The shared code I work with always uses "../" though so I'd prefer a solution that gets that to work instead so that I don't have to change the original script each time I need to use it.
Thank you very much.
Edit: Despite the conversation below, I am still having trouble with this. I tried setting the working directory and then using "../" and it sometimes works for read_xls() (it was working a few hours ago, not anymore, depsite doing the exact same thing and setting the same working directory) but not for rio::import() or other reading functions. I've even tried setting my working directory to the exact same folder and using "./" but no luck. Errors now say "Cannot open the connection" or "No such file"

You can try setting your working directory(wd) to the current folder first, then use read.csv to import the data.
To set the working directory, first obtain the current directory using rstudioapi::getActiveDocumentContext()$path then use setwd() to set the wd to this path.
Then use whatever function to import your data.
For example, let's say your R code is saved in the "branch" folder, then the following code should work just fine:
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
mydata <- read.csv("./file_name.csv")
head(mydata)
Otherwise, if your R code was saved in a subfolder under Folder2 called code such that your R script's directory is: "C:/Users/Name/Dropbox/Folder1/Folder2/code/mycode.R", then the following should work:
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
mydata <- read.csv("../data/branch/file_name.csv")
head(mydata)

It looks like the person you are collaborating with has their working directory set to a separate folder within Folder2 (perhaps a folder with all the .R code?). The .. means that the relative path is referencing the next folder up from the working directory (the next folder up is presumably Folder2).
To solve your problem, every time you start working you need to set your working directory to the same folder that your collaborator is using for their working directory. For example, this may be something like setwd("C:/Users/Name/Dropbox/Folder1/Folder2/RCode"). Unfortunately you will have to do that every time you open up the script, but if you do it at the very beginning, then the rest of the code should work.
Working directories can be hard to manage, especially when collaborating. A better solution to the working directory problem is to create a project in R Studio and collaborate on that project using GitHub. If you don't have experience with GitHub, these videos are an approachable resource for helping you get started.

Related

Why is RStudio telling me that my file doesn't exist? I'm looking directly at it

I'm on RStudio, just wanting to read a csv file:
newdata <- read_csv("Nameofdata.csv",
col_names = TRUE)
But it keeps telling me that the file doesn't exist. It does exist. I'm staring DIRECTLY at it, underneath the file path that RStudio insists is wrong. I can open it in another tab, I can open in in excel, it's EXACTLY where RStudio says it's not existing. Please help.
Looking very closely at your screen shot, commenters are suggesting that you have an extra space at the beginning of your file name.
Also, I see that the working directory appears to be correct (the error message lists it as C:/users/mdavi/Desktop/School/Research/Sc, which appears to match what is listed in the Files pane
A couple of strategies for trouble-shooting file-locating problems:
use getwd() and list.files() to confirm your working directory and what files R can see from there (you can read this introduction to get more background on working directories):
use file.choose() to select a file interactively; it's generally a bad idea to use this in production code, as it will add an interactive step when you usually want to be able to run all of your code start to finish without needing manual steps, but it's quite useful for debugging.
If you wanted R to list files that approximately matched your specified filename, you could use
L <- list.files(pattern="*.csv")
agrep("myfile.csv", L, value=TRUE)
You need to set your working directly correctly, either via setwd("~/Desktop/School/Research/SC") in the R Console (that's what I think I see in your screenshot: ~ stands for your home directory, i.e "Users/Whoever") or via Session > Set Working Directory > To File Pane in the RStudio menus.
You can read a variety of Stack Overflow questions about setting the working directory for more complete context ... web searching on "R 'working directory'" might help too.

R: importing data impossible (windows)

I used to work with R on my mac and never had any problems.
Now I would like to use it on my work computer (windows). The problem is I can't import any files to start working with them. I tried several options:
mydata<-read.table("c:/temp/myfile.csv",header=TRUE)
mydata<-read.csv("myfile.csv",header=TRUE)
mydata<-read.table("c:/myfile.csv",header=TRUE)
mydata<-read.table("Desktop/myfile.csv",header=TRUE)
I also tried to change / into \ in all variants above.
Nothing seems to work. R displays the command in red, sometimes with a comment "connection can't be opened" or "no such file or directory" (my translation from German).
I tried copying the file I want to open to a different location (desktop, c:, temp), but alas, nothing helps.
Do you have any ideas why I have this problem and how I can solve it? Thanks in advance.
There is a safer way to work with paths; just using file.path().
So, if you're trying to get a file in C:/temp/turtles.csv, then you'd use:
targetFile <- file.path('C:/', 'temp', 'turtles.csv')
read.csv( targetFile, header=TRUE )
Minor point since it showed up on Twitter; DO NOT USE PATHS THAT EXIST ONLY IN YOUR ENVIRONMENT.
Try to keep the data in a path either in or directly under where the script is.
You have three ways to do this with read.csv() function
To avoid inserting actual path you can do it simply nesting function
read.csv(file.choose(),header=TRUE)
it will open pop up for selecting your file just select file from directory
where you have saved it.
Now if you have to insert a path then just get actual location of your file
by
read.csv("C:\path\to\your\file\filename.csv",header=TRUE)
for Example
read.csv("C:\Users\Amway\Desktop\resources.csv",header=TRUE)
Best way is to have your own work space directory
so create a directory by your preferred name and just set that directory as a
R session work space by
setwd("C:\path\to\your\workspace directory\")
check your current directory by
getwd()
now if you want to read a file into R session just copy your file to work
space and just write
read.csv("resources.csv",header=TRUE)
So, it should be like this.
setwd("c:/mydir") # note / instead of \ in windows
Also.
MyData <- read.csv(file="c:/mydir/TheDataIWantToReadIn.csv", header=TRUE, sep=",")
Windows uses the other backslash.
https://www.howtogeek.com/181774/why-windows-uses-backslashes-and-everything-else-uses-forward-slashes/

Reading data files in blogdown

I am a new user of blogdown using Hugo. I would like to create a new post that includes R code to read a data file.
The data file is in my static folder, local path C:\mydir\myblogdown\static\data\savedrecs.txt. Since I was successful in referring to an image using a relative path like this, ![](/images\myimage.jpg), I tried reading the data using something similar for the data file, read.csv("/data\savedrecs.txt"), but that didn't work.
I started playing around with the list.files() function to see if I could find a relative path that worked in my local version of the post, list.files("../../static/data") worked, showing me ## [1] "savedrecs.txt".
I tried searching around other folks' blogdown repos on Github to see how they might have referred to a data file, but the only example I found referred to a data file using a URL.
I suspect that this may be due to the location of your data file. In my working example, the Rmd form of my blog post is in the directory, called p0bs/content/post. I also add my data file (a CSV in my case) to this directory.
I then treat the rest of the post as I would in a standard Rmarkdown website, with Rmd chunks (that are named without spaces). In your case, that code would include:
read.csv("savedrecs.txt")
I hope that helps you.

How do I assign the working directory for rmarkdown/knitr interactive doc on shinyApps.io?

I have a fully functional interactive shiny doc using knitr/r markdwon.
However, when I try to publish (deploy) it to shinyApps.io, I get an error saying the .PNG file I try to incorporate into the doc (using readPNG from the png package) is unable to open.
I know the problem is related to working directories.
In my original code I assigned a working directory to my folder (i.e., "C:/Users/NAME/documents/...." that contains both my .rmd file and my .png file. However, obviously my folder doesn't exist on the shinyapps.io.
So how exactly do I set my working directory to open the .png file via my doc on shinyapps.io?
I can't find anywhere that explicitly walks through this process. Please help explain this simply/basically for me.
Example:
Assume I have a folder in "C:/Users/NAME/documents/Shiny" that contains 2 files: "shiny.rmd" and "pic.png". I want "pic.png" to be rendered in my shiny.rmd doc.
Currently I have:
---
title: "TroubleShoot"
output: html_document
runtime: shiny
---
```{r ,echo=FALSE,eval=TRUE}
library(png)
library(grid)
direct <- "C:/Users/NAME/documents/Shiny/"
img <- readPNG(paste0(direct,"pic.PNG"))
grid.raster(img)
```
How do I rewrite my code so it works on shinyApps.io?
Do I need to create and name folders in specific ways to place my 2 files into before deploying?
When you paste the c drive to direct, and read the direct into img, you are sending the app/markdown to your local drive. You need to use a relative path to the project. I would suggest something like:
direct <- "./"
Which uses the relative path, not the absolute path.
That said you might be able to skip that step entirely if the .png is in the same folder as the shiny object. just call the file name and format and leave it as that.
Also, check you use of ". Your syntax highlighting indicates your code won't run properly as it thinks some of your functions and variables are character strings because you've misplaced your quotes around read.png(). That's probably just a copy and paste typo though.
In summary, call the image via grid.raster("./pic.PNG"), and brush up on how working directories and relative paths work.
In the absence of knowing exactly how you're 'setting' your working directory:
In rStudio to correct and easiest approach is to make a 'New Project' for every New Project. You can do this as the first step in your project, or you can add a project file to an existing directory.
When you do this it automatically sets your working directory correctly. The way you seem to be doing it is not correct, you are merely supplying a 'path'. If you were to not want to use a project for some reason (I can't think of a case where that would be right), then you can always use setwd(), however, I believe this needs to be used in every session. A true project doesn't have that requirement.
This will then allow you to deploy your app properly as it will update the working directory to the one on the host machine at shinyapps.io when it is initialised there.
Finally, using the correct relative syntax "./path/to/my.file" to reference all your assets, images, data etc, should correct your issue as stated in the question.

Calling Skim from inside R

I'm making a simple line in r to automatically open my generated plots.
I output the plots to a file called "plots.pdf" in the same directory as my r file, and at the end i use this two lines to try to open it:
dir <- paste("/Applications/Skim.app/Contents/MacOS/Skim ",getwd(),"/plots.pdf",sep="")
system(dir)
Basically, dir concatenates the full path of the skim app and the full path of the generated plot.
If i run the string stored at dir in a shell it works perfect, it opens the pdf file in Skim, but when i run it with system() from inside R it doesn't work (Skim says 'The document “plots.pdf” could not be opened.').
I believe this is a very little mistake somewhere in the syntax regarding the absolute/relative paths, but haven't managed to find it... Any advice is welcome! (Or a better way to achieve the same)
I found a way to bypass that problem, i just changed the path to Skim for the 'open' command and i let the system to assign the default app for pdf viewing. So:
dir <- paste("open ",getwd(),"/plots.pdf",sep="")
And it works.

Resources