Filepath error when specifying output location for write_dta - r

I would like to programmatically specify the location of my exports when using write.dta. I have my working directory set to a parent folder and my script is in a child folder called "Script". I want the export to be in a child folder called "Data".
setwd("~/Dropbox/Files")
file_output <- "survey"
path_out <- "./Data"
write_dta(df, paste0(file_output,".dta"), path = path_out, version = 12)
However, I keep getting an error message when R is trying to write. It says it's trying to write to the "Script" folder (where my script file is located in) rather than the desired "Data" folder.
Error: Failed to open '/Users/VancityPlanner/Dropbox/Files/Scripts' for writing
If I put the full path, I still get the same error message, whether it's a child folder or the parent folder (working directory) itself, so I don't think write permissions are an issue.
If I try not specifying the filepath, I have no error messages but it saves it to my working directory, which is not where I want it.
write_dta(df, paste0(file_output,".dta"), version = 12)

Below I show where my working directory is pointing and then I change the path of where I want to save the document in the path statement. Note it has the file path G:/ and the dataset name appended all together. I have a PC but no reason why this shouldn't work on a mac.
library(haven)
getwd()
#"C:/Users/myname/Documents"
write_dta(data = mtcars, path = "G:/mtcars.dta", version = 12)

Related

FS package not detecting folder in R project

I'm running a shiny app using flexdashboard but having trouble adding images to the app. The folder containing the images is not being recognized. Here is my folder structure -
Root_Project
-- \app
--- \app_R
---- app.Rmd
---- \bike_img
----- \product_id_37417.jpg
Inside my project, I have a folder called app
Inside app, I have another folder called app_R.
Inside app_R I have a app.Rmd file (which contains the code for the app) and another folder called bike_img (which contains a .jpg file)
In the app.Rmd, I have the following code chunk (after the hashtag is just a comment explaining what the code is doing) -
renderPrint ({
id = "37420" #an id string
dir_files <- fs::dir_ls("bike_img/") #list all files in the bike_img directory
dir_res <- dir_files %>% str_detect(detect_product_id) #detect any file containing the id string
dir_files[dir_res] #return the file containing the id string
})
When I run this in the console, I get the required result which is bike_img/product_id_37420.jpg. However when I run the app, I get the following error
Error: [ENOENT] Failed to search directory 'bike_img': no such file or directory
There seems to be an issue detecting the bike_img folder. Not sure if this is an issue with my code or the {fs} package.
Can anyone see what I may be doing wrong??

Running a same script in sub folders

In my main folder i have many sub folders like AA,BB,CC,DD ...etc. and all folders have a common script named run_script.R and i want to run this script in every folder. folder can be any amount.
Its working abut running in first folder only ,but i wanted it to run in every folder.
also when i am using setwd(folder) then showing error
Error in setwd(folder) : cannot change working directory
data_folder <- "C:/Users/mosho/Desktop/New folder (2)/"
allfolders <- data.frame(Folders = list.dirs(path = data_folder, recursive = F, full.names = F))
r_scripts <- "run_script.R"
for (folder in allfolders$Folders) {
#setwd(folder)
message(folder)
source(paste0(data_folder,folder,"/",r_scripts))
}
You are on a right path, I did some minor tweaks to your script which will resolve the issue. The points missing in your scripts are;
the allfolders contains the folder name not the entire explicit path. To set the working directory you need to set give the explicit path, by only calling the folder name will result into error unless you existing working directory is contains that folder. Anyways, its best practice to work with full path names.
also to simplify setting up allfolders as list for iterator will make your life lot easier than a data frame
Below is my work-out;
I created some dummy folders (DIC01, DIC02, DIC03...) under path "C:\Users\XXXXXX\Documents\TEST MAIN", and placed code run_script.R inside each one. This run_script.R contains simple code print("Hello World !!")
Next I set initial working directory where to the path where all the folders present i.e. to path "C:\Users\XXXXXX\Documents\TEST MAIN". Next listed the folders/directories present within this path as a list instead of data frame. Next is for loop which iterate over list of folder names. Inside we reset the working directory by the folder name and source the R code.
data_folder <- "C:\\Users\\XXXXXX\\Documents\\TEST MAIN"
setwd(data_folder)
allfolders <- list.dirs(path = data_folder, recursive = F, full.names = F)
r_scripts <- "run_script.R"
for (folder in allfolders) {
print(folder)
setwd(paste0(data_folder,"\\",folder))
source(paste0(data_folder,"\\",folder,"\\",r_scripts))
}
The result I get after the execution is something like this. First the name of the directory and then execution result.
I hope this resolves you problem. If yes Like/Up vote the answer and let me know.

Attempting to access images using R

So I am following the guide here which indicates the way to access photos is as follows:
flags <- c(
system.file("img", "flag", "au.png", package = "ggpattern"),
system.file("img", "flag", "dk.png", package = "ggpattern")
)
My goal is to now use this code for my own uses, so I saved a few images in a folder. Here is my directory:
"C:/Users/Thom/Docs/Misc/Testy"
And within the Testy folder, there is a folder called image, holding 3 images. But the following doesn't seem to work and idk why...
images <- c(
system.file("image", "image1.png", package = "ggpattern"),
system.file("image", "image2.png", package = "ggpattern")
)
system.file is for use when a file included in a package. Basically, it will look for the file starting its search path to where your R packages are installed (because this can vary from user to user). system.file will return the resolved path to the file locally
If you already know the absolute path on your local computer (i.e. "C:/Users/Thom/Docs/Misc/Testy") you can use that as just the input to a read function, e.g. readBin("C:/Users/Thom/Docs/Misc/Testy")
If you want to get a little fancy or are like me and can't ever remember which direction of a slash to use on which OS, you can also do something like this which will add in the OS specific path separator:
readBin(file.path("C:", "Users", "Thom", "Docs", "Misc", "Testy"))

file.create syntax

Super big newbie to R. I'm a bit stuck on the file.create function. I've used it successfully to create a file in the set working directory and also when I've already created a separate file path and assigned that file path to a variable.
However, why can't I use file.create and simply list the desired file path and file name without the file.path function? Does the file.create function not possess the capacity to automatically create the file in the specified directory, but requires the file.path function to secure the path to the directory?
Any clarification would be greatly appreciated. I do apologize if this question is rather elementary but I'd like to get the fundamentals down.
Here's the code that worked:
BasicDir <- "/Users/slam1924/Desktop/LearnR Tutorials"
setwd(BasicDir)
file.create("myfile.doc")
fp1 <- file.path("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc")
fp1
file.create(fp1)
Alternative:
file.create(file.path("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc"))
Here's the code that failed:
file.create("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc")
Start by reading the help for the function. help(file.create). The usage is file.create(..., showWarnings = TRUE)
Under Details you'll see
file.create creates files with the given names if they do not already
exist and truncates them if they do.
So when you try
file.create("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc")
It's trying to create two files, one of which ("/Users/slam1924/Desktop/Vocal Covers") is likely already a directory.
If the file or directory already exists, you'll see an error like:
[1] FALSE
Warning message:
In file.create("data") :
cannot create file 'data', reason 'Permission denied'
You could fix this by sending the function one string. Change your code that failed to:
file.create("/Users/slam1924/Desktop/Vocal Covers/mytext.doc")

Why doesn't knitr respect RStudio project details?

In all other cases, when I am working within an RStudio project, I can make references relative to the project root in scripts. So I can, for example, dfX = read.csv("Data/somefile.csv"), where the folder Data is relative to my project root.
The same code in a knitr chunk does not find the file. I guess this is because knitr creates a bunch of temporary directories that it needs to refer to relative to the file location. Is there an easy way to change this behavior? Obviously, I would not like to add the entire path to the project folder -- I am aware that I can easily do this using knitr::opts_knit$set(root.dir = rootPath). That completely breaks maintainability across machines and OSs.
Edit: This seems closely linked to this question.
Presumably you know the path to the package directory when you call 'knit', so how about:
ENV <- new.env()
assign("workingDirectory", getcwd(), envir = ENV)
knitr::knit(...,
# THE ENVIRONMENT IN WHICH THE CODE CHUNKS ARE TO BE EVALUATED
envir=ENV)
Then in your rmd file you can do:
```{r] print(workingDirectory)```
If you're searching for the location of the current install, you can use:
PATH = NULL
for(libPath in .libPaths())
if('myPackage' %in% list.dirs(libPath,FALSE,FALSE)){
PATH = file.path(libPath,'myPackage')
}
if(is.null(PATH))
stop('could not find package directory')
ENV <- new.env()
assign("workingDirectory", PATH, envir = ENV)
knitr::knit(...,
# THE ENVIRONMENT IN WHICH THE CODE CHUNKS ARE TO BE EVALUATED
envir=ENV)
My guess is that the document that you are "knitting" is in a subdirectory itself. It seems that, when you click "Knit PDF", RStudio or knitr will setwd() to the directory containing the file being knitted. So you may need to do something like dfX = read.csv("../Data/somefile.csv") to get the reference right.
I have a working example here.

Resources