Let's say this is the working directory where my R script is residing:
C:/Users/Indrajeet Patil/Dropbox/Study 1/Data analysis
I know how to create a new directory inside the current working directory-
dir.create(path = paste(getwd(), '/Results', sep = ''))
What I am struggling with is how to tell R to move one folder backward and create a new directory. So, in this example, I want to create a new folder inside the folder Study 1 and call it Results.
To go back once you need to add .. to the beginning of the path as in
dir.create(path = '../Results')
Related
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.
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)
I am trying to upload hundreds of googlesheets using the new R googlesheets4 package using the function gs4_create. I can successfully upload files in the root of the google drive but fail to see how I can send it inside a pre existing folder on google drive.
See the following reprex:
df <- data.frame(a=1:10,b=letters[1:10])
googlesheets4:: gs4_create(name="TEST_FOLDER/testsheet",sheets=df)
It creates a file named : "TEST_FOLDER/testsheet in the root folder.
While I want to create the file inside the TEST_FOLDER.
I know I can use write_sheet() on files pre existing inside a folder but I want to create new files, not write in pre existing files. I also know the googledrive::drive_upload() will allow me to upload csv files but I do not like the format of the csv files when they are uploaded, as they go as plain text sheets with no frozen first row. This is possible only through the googlesheets4 package. So back to my question:
How do I create a googlesheet files (in bulk) inside the TEST_FOLDER?
First, you have to create a folder with drive_mkdir(name = "TEST_FOLDER") from the googledrive package. Once you created it, I would recommend you to work with the ids of the folder and the files. So, the next step to find the id would be:
folder_id <- drive_find(n_max = 10, pattern = "TEST_FOLDER")$id
*This works if you have only one folder called TEST_FOLDER in your Google Drive. If you have more than one, i would recommend you to copy/paste the id directly, or identifying the id you want before assigning to the "folder_id" object.
*If you don't want to do this step, you can also copy/paste the id directly from the Google Drive url
Once you have it, you can program a for loop in order to upload all files. For example, supposing your sheets are called sheet1, sheet2... sheet10:
a <- rep("sheet",10)
b <- 1:10
names <- paste0(a,b)
for(x in names){
gs4_create(name = x, sheets = list(sheet1 = get(x)))
sheet_id <- drive_find(type = "spreadsheet", n_max = 10,
pattern = x)$id
sheet_id <- drive_find(type = "spreadsheet", n_max = 10,
pattern = x)$id
drive_mv(file = as_id(sheet_id), path = as_id(folder_id))
}
NOTE: If you have too many files in your root folder of Google Drive, the mkdir function will take too much time. That's why I recommend working with ids. If you have this problem, you could create this folder manually, copy the id and assign it to the "folder_id" object.
I have tried looking at File extension renaming in R and using the script without any luck. My question is very much the same.
I have a bunch of files with the a file extension that I want to change. I have used the following code but cannot get the last step to work.
I know similar questions have been asked before but I'm simply stuck and therefore reaching out anyway.
startingDir<-"/Users/anders/Documents/Juni 2019/DATA"
endDir<-"/Users/anders/Documents/Juni 2019/DATA/formatted"
#List over files in startingDir with the extension .zipwblibcurl that I want to replace
old_files<-list.files(startingDir,pattern = "\\.zipwblibcurl")
#View(old_files)
#Renaming the file extension and making a new list i R changing the file extension from .zipwblibcurl to .zip
new_files <- gsub(".zipwblibcurl", ".zip", old_files)
#View(new_files)
#Replacing the old files in the startingDir. Eventually I would like to move them to newDir. For simplicity I have just tried as in the other post without any luck:...
file.rename( old_files, new_files)
After running file.rename I get the output FALSE for every entry.
The full answer here, including comment from #StephaneLaurent: make sure that you have full.names = TRUE inside the list.files(); otherwise the path to the file will not be captured, just the file name.
Full working snippet:
old = list.files(startingDir,
pattern = "\\.zipwblibcurl",
full.names = TRUE) #
# replace the file names
new <- gsub(".zipwblibcurl", ".zip", old )
# Rename old files names to the new file names
file.rename(old, new)
Like #StéphaneLaurent said, it's most likely that R tries to look in the current working directory for the files and can't find them. You can correct this by adding
file.rename(paste(startingDir, old_files, sep = "/"), paste(newDir, new_files, sep = "/"))
For working purpose, I have made a new function which automatically tests whether a folder (with its name specified by its file path) exists or not:
make.dir <- function(fp) {
# If not existing, create a new one
if(!file.exists(fp)) {
make.dir(dirname(fp))
dir.create(fp, recursive = FALSE, showWarnings = FALSE)
} else {
# If existed, delete and replace with a new one
unlink(fp, recursive = FALSE)
dir.create(fp)
}
}
An example would be:
make.dir("D:/Work/R/Sample")
this is supposed to create a folder named "Sample" in the parental folder "R" if that folder did not exist, and replace the folder with a new one, if existed.
However, I have only been trying this with the latter case, i.e. replacing existing folders. Yesterday, I used this code to try to make a folder that did not pre-exist in "Sample" folder (say "Plots"). Instead of creating a folder named "Plots", it detected that the parent folder - "Sample" existed and started to delete every files contained in that folder. Afterwards, it proceeded to delete all of the files in the upper folder - "R" - as well. I had to cancel the code before it deletes my (D:) drive.
It works fine for replacing existing folders, but not with creating new folders. Anyone has any ideas on how to fix the function, or make a new one?
Thanks
As pointed out by #ytk in the comment above, the call for make.dir in the first if statement makes the function go wild. Removing that solved the problem. Thanks, ytk