setwd() works weird inside a function? - r

I have a function for choosing files using file.choose(). When I call it inside a script I want it open certain directory where I wish to choose files. There is a cycle inside the function as I need to choose a bunch of files. First time it opens in the working directory, which is predictable. I put setwd() inside to make the needed directory as working directory so I can choose files there. But when dialog box opens next time it is again the old working directory. But next time it is the directory I need. If I choose different folders it works the same - next time the old directory but after that the new one. I wrote a short function that reproduces behavior:
foo <- function() {
files <- NULL
for (i in c(1,2,3,4,5)) {
x <- file.choose()
y <- dirname(x)
setwd(y)
print(y)
print(getwd())
}
}
Just call this function and try to choose files in different or same directories. You can see that directory name is new and getwd() says that new working directory is set but next file choice dialog opens in previous directory.
Please keep in mind that I need to use file.choose() function as it works on a headless OS, both Windows and Unix-like.
When I don't use setwd() it is always the old working directory.

Related

"../" relative path directory not working 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.

Upload files in a folder without referencing name with R

I do not know how to create a reproducible example of this issue since it would require access to a folder on my computer(if anyone has a suggestion I am fine to follow up). However, what I would like to do is upload a file in a folder without actually referencing the name but only referencing the order it appears in the file, and I would like to do it in R if possible(although python would be fine as well). I want to do this because the folder has 40 or so files and I need to format them all the same, but they all have different names.
In other words I want a code that would look something like this:
setwd(folder)
for(i in 1:number of files in folder){
upload file i
process file i
rbind(master file,file i)
}
Obviously this is not an actual code, but merely a framework, so I did not put it in the code framework on the site. The line I do not know how to do is the first line in the loop(download file i). Is it possible to do this, or do I need to download every file individually with their specified name?
I think you're looking for list.fles()
ff <- list.files()
for(i in seq_along(ff)){
print(ff[i])
read.csv(ff[i], ...) # etc
...
}

R - Specify the directory using the package googlesheets

I use the googlesheets package. The default directory for spreadsheets is the root of Google Drive. I guess that I can specify the directory - like for a "normal" directory path - but I don't know how to do that.
gs_new(title = "MyData") # export to the root
gs_new(title = "Something/MyData") # export to the specified directory
I'm also interested in this question. I will try the following to see if it works. If not, I may try to use the 'googledrive' package on top of, or in replacement of, the 'googlesheets' package to do sheet creation in a list folder hierarchy. This way I can loop through a list of subfolders while creating any files inside them until all subfolders have their new files created.
So here's my thinking... When I have time to test this out, I'll let you know!
for(path in file_paths){
setwd(path)
for(file in files){
gs_new(file)
}
}
Of course, get your parent folder as a string and use list.files("string", full.names=TRUE). Then, if you have any subfolders (assuming they're created already), it'll return a list in which to loop through. If you just want to create one workbook at one location, simply setting the working directory might work. Again, I'll need to test this in multiple methods.

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.

R: setwd delay when using file.choose

So what im doing is making my browse button so that when i click on them bring the user straight to the directory that i want them to save their file in or look for their file.
For example
setwd("C:\\Users\\Eric\\Desktop\\Program\\graphs") #set directory
file.choose()
However in the earlier script i have already set my work directory at
setwd("C:\\Users\\Eric\\Desktop\\Proram") #set directory
so when i ran the first example it brought me to directory Program instead of graphs .
but when i ran file.choose() on the second time, it then brought me to the graphs directory
why is this happening? any idea how to fix this ?
Here's a quick and dirty solution to your problem:
dirPath <- "C:\\Users\\Eric\\Desktop\\Program\\graphs"
setwd(dirPath)
# Tell R to sleep until the current directory matches the expected directory
while(getwd() != normalizePath(dirPath)) {
Sys.sleep(0.02)
}
file.choose()

Resources