How to move backward parent folder - r

In R, I'm working on "./parent/Child/A". I want to move back parent folder "child", but when I type full path. It lost many times.

setwd('..')
will move up one directory without entering the absolute path. Here's an example
> getwd()
[1] "C:/Users/D/Desktop/EDABaseball"
> setwd('..')
> getwd()
[1] "C:/Users/D/Desktop"

I think you want to move back to the working directory ./parent/Child/. This can be done in 2 ways, assuming your current working directory is ./parent/Child/A
1) setwd("..")
2) setwd("./..")
3) setwd("./parent/Child")

I also find dirname() function pretty useful especially if your path is saved in a variable:
mypath <- getwd()
# The path of the parent directory:
dirname(mypath)

Moves up one directory in Linux
setwd("../")

Basically I split the child folder using strsplit by '/' and then got the parent folder pasting the slices collapsing by '/', except for the last one. I used getwd() to make the code reproducible, but you may use any folder.
myDir <- unlist(strsplit(getwd(), '/'))
paste0(myDir[-length(myDir)], collapse = '/')

Related

Coding a relative path to a shared directory in R

Let's say my colleagues and I have a shared directory, such as a SharePoint drive. Our file path to any given directory, say OurProject1 will be the same with the only difference being our username.
So for example my path will be: "C:/Users/JohnLennon/SharedDrive/SharedData/baseline_data"
While theirs will be: "C:/Users/RingoStarr/SharedDrive/SharedData/baseline_data"
I am trying to write a function that will allow any of my colleagues who has mapped the shared drive to run a script that accesses data in the shared data without them having to manually input their username. Keep in mind that the project directory is not the shared drive - that if I share this script with a colleague it will be kept outside of the shared directory and so relative file paths with regards to the project won't work.
I have been trying to approach this using an absolute file path set temporarily within the function that infers the first half of the directory path from getwd(). So the function looks a bit like this:
wd <- getwd() # get the users working dir
usr <- substr(wd, 1, 18) # extract the root down to the username
paste(usr, "SharedDrive/SharedData/baseline_data", sep = "") # prefix this onto the shared directory path
This works fine for RingoStarr, who has the same number of characters in his username as JohnLennon, but what about GeorgeHarrison, or all the other users? Counting characters on line two is clearly a limited approach.
I am looking for a modification to line two that will navigate "blindly" from the working directory, which we assume to be a subdirectory of "C:/Users/Username/" to two levels below the root directory (i.e. in the Username directory). ".." won't work here as we don't know where abouts within the the Username directory getwd() is.
I am also open to a different approach to the problem if one exists
Instead of substr, you can try strsplit and then paste with the collapse argument:
wd_split <- strsplit(wd, "\\/")
wd_split
# [[1]]
# [1] "C:" "Users" "JohnLennon" "SharedDrive" "SharedData"
usr <- paste(wd_split[[1]][1:3], collapse = "/")
usr
# "C:/Users/JohnLennon"

R: list.files() does not find files in "special folder"

I have the following problem: I want to list all files recursively in a given folder. But this folder contains a somehow special folder, where list.files() can't look into. However, fs::dir_ls() is able to look into the folder. See the example:
> list.files(path, recursive = TRUE)
[1] "???" "archive_folders.R"
[3] "archived_folder/archived_file.txt"
>
> dir_ls(path, recurse = TRUE)
U:/Eigene Dateien/R/archive_folders/archive_folders.R
U:/Eigene Dateien/R/archive_folders/archived_folder
U:/Eigene Dateien/R/archive_folders/archived_folder/archived_file.txt
U:/Eigene Dateien/R/archive_folders/ааа
U:/Eigene Dateien/R/archive_folders/ааа/archived_file.txt
I'm working on Windows 7 and looking into the properties of the aaa folder did not give a hint about the problem. So my question is twofold:
Any ideas on what might be so special with the aaa folder?
Is there any possibility that list.files() can find the files inside this special folder?
EDIT:
The name of the folder ааа is in fact not aaa. Sounds confusing? The folder's name consists of U+00430, not the usual letter a (U+0061).
I had a similar problem. I don't know why but list.files() simply didn't work on my previous computer. I solved it using dir(). This function is loaded onto base R.
dir(path, recursive = TRUE)
Otherwise, you can try this to see if changing the working directory changes the result:
setwd(path)
dir(, recursive = TRUE)
list.files(, recursive = TRUE)
As for your question regarding the folder, I have no idea why this happens.

How to loop over each file in multiple directories in R

I have an object called wanted.bam with the list of wanted file names for all the .bam (is the extension) files in three of my directories path1,path2,path3. I am looping over all these directories to search for the wanted files. What I am trying to do is look for wanted files by looping over each directory and implement a FUNCTION in each file. This loop works for all the matched file in the first directory, but as it progresses to another directory, it breaks giving an error:
Error in value[[3L]](cond) :
failed to open BamFile: file(s) do not exist:
'sort.bam'
my code:
bam.dir<- c("path1","path2","path3")
for (j in 1:length(bam.dir)){
all.bam.files <- list.files(bam.dir[j])
all.bam.files <- grep(wanted.names, all.bam.files, value=TRUE)
print(paste("The wanted number of bam files in this directory:", (length(all.bam.files))))
if(length(all.bam.files)==0){
next
}else{
setwd(bam.dir[j])
}
print(paste("The working directory number:",j,":",(getwd())))
## ****using another loop here for each file to implement a function*****
all.FAD<- {}
for(i in 1:length(all.bam.files)){
output<- FUNCTION(all.bam.files[i])
}
}
You probably don't want to be changing working directory like this. Instead, use the option in list.files, full.names=TRUE, to return the full path of your files. Then, you can just use read.csv, or whatever, on the full path name without need to change directory. Your code is failing because after you set directory, the relative path to the next directory is changed.
If you want to keep changing directories, just make sure you set the directory back to the base directory at the end of the loop.

Parent directory in R

How do I get the path to parent directory in R?
I have to write an R script that takes input from a directory in the parent directory and outputs data into another directory in the parent folder. So, if I could find path to parent folder, then I could do this.
You can use dirname on getwd to extract everything but the top most level of your current directory:
dirname(getwd())
[1] "C:/Documents and Settings"
Actually dirname allows to go back to several parent folders
Path="FolderA/FolderB/FolderC/FolderD"
dirname(Path)
"FolderA/FolderB/FolderC"
dirname(dirname(Path))
"FolderA/FolderB"
And so on...
I assume you mean parent directory of R's working directory?
The simplest solution is probably as follows.
wd <- getwd()
setwd("..")
parent <- getwd()
setwd(wd)
This saves the working directory, changes it to its parent, gets the result in parent, and resets the working directory again. This saves having to deal with the vagaries of root directories, home directories, and other OS-specific features, which would probably require a bunch of fiddling with regexes.
Possibly these two tips may help
"~/" # after the forward slash you "are" in your home folder
then on windows
"C:/" # you are in your main hard drive
"G:/" # you are just in another hard drive :-)
on unix you can do something similar with
"/etc/"
then you can go down into any sub directory you need
Or as #Hong Ooi suggests you can go up to the parent dir of your working directory with
"../"
NB: just after the final forward slash press tab and you'll have all the file and folder, very handy, especially in RStudio
Another possibility:
parts <- unlist(strsplit(getwd(), .Platform$file.sep))
do.call(file.path, as.list(parts[1:length(parts) - 1]))
This splits the filepath into directories, drops the last directory, and then recombines the parts into a filepath again.
You could simply use ".." like output_dir <- paste(input_dir, "..", "out", sep = .Platform$file.sep), or using the fs package (install.packages("fs")):
input_dir <- "base/input"
parent_dir <- fs::path(input_dir, "..") # "base/input/.."
output_dir <- fs::path(input_dir, "..", "out") # "base/input/../out"
# to shorten the path (avoid "input/../") you could use `fs::normalize`:
fs::normalize(fs::path(input_dir, "..", "out")) # "base/out"
# in case input is a symlink and you want the parent directory of the target, look at `fs::real`
In RStudio you could navigate to your code directory and "Set As Working Directory" in Files. And then ".." will work.

Moving files between folders

I want to copy/paste a file from one folder to another folder in windows using R, but it's not working. My code:
> file.rename(from="C:/Users/msc2/Desktop/rabata.txt",to="C:/Users/msc2/Desktop/Halwa/BADMASHI/SCOP/rabata.tx")
[1] FALSE
If you wanted a file.rename()-like function that would also create any directories needed to carry out the rename, you could try something like this:
my.file.rename <- function(from, to) {
todir <- dirname(to)
if (!isTRUE(file.info(todir)$isdir)) dir.create(todir, recursive=TRUE)
file.rename(from = from, to = to)
}
my.file.rename(from = "C:/Users/msc2/Desktop/rabata.txt",
to = "C:/Users/msc2/Desktop/Halwa/BADMASHI/SCOP/rabata.txt")
Please just be aware that file.rename will actually delete the file from the "from" folder. If you want to just make a duplicate copy and leave the original in its place, use file.copy instead.
Use file.copy() or fs::file_copy()
file.copy(from = "path_to_original_file",
to = "path_to_move_to")
Then you can remove the original file with file.remove():
file.remove("path_to_original_file")
Update 2021-10-08: you can also use fs::file_copy(). I like {fs} for consistent file and directory management from within R.
You can try the filesstrings library. This option will move the file into a directory. Example code:
First, we create a sample directory and file:
dir.create("My_directory")
file.create("My_file.txt")
Second, we can move My_file.txt into the created directory My_directory:
file.move("My_file.txt", "My_directory")
You are missing a "t" letter in the second extension. Try this:
file.rename(from="C:/Users/msc2/Desktop/rabata.txt",to="C:/Users/msc2/Desktop/Halwa/BADMASHI/SCOP/rabata.txt").
Additionally, it could be worth it to try the file.copy() function. It is specifically designed to copy files instead of renaming.

Resources