3

I want to get the parent directory from a folder path.

say I have: "C:/Users/YS/2020 projects/APP/pect/PDC/src"

and I want to get: "C:/Users/YS/2020 projects/APP/pect/PDC"

#Get current directory
cpath = getwd()

#Remove last folder from path
dir <- strsplit(cpath,"/")
dir <- dir[[1]]
parent_dir <- dir[1:length(dir)-1]

#Return file path
file.path(parent_dir)

These are my environment variables:

enter image description here

and here is the output I get from the code:

[1] "C:"            "Users"         "YS"            "2020 projects" "APP"           "pect"          "PDC"    

I want it to return:

[1] "C:/Users/YS/2020 projects/APP/pect/PDC"

Why can't I pass a list of characters into file.path()?

I'm a little confused by how dir in my environment variables is listed as a character not a list or vector

I'm also a little confused by why strsplit returns a list with 1 value in it?

Pythonner12
  • 123
  • 1
  • 1
  • 8

2 Answers2

1

If we want to remove the "src", an option is sub

sub("[/][a-z]+$", "", cpath)

If we want to use file.path, where the usage is

file.path(..., fsep = .Platform$file.sep)

The ... implies multiple arguments passed one by one, i.e.

file.path(parent_dir[1], parent_dir[2])
#[1] "C:/Users"

and so on

parent_dir
#[1] "C:"            "Users"         "YS"            "2020 projects" "APP"           "pect"          "PDC"         

If we want to replicate that, an option is to place it in a list and use file.path with do.call

do.call(file.path, as.list(parent_dir))
#[1] "C:/Users/YS/2020 projects/APP/pect/PDC"

Or with Reduce

Reduce(file.path, as.list(parent_dir))
#[1] "C:/Users/YS/2020 projects/APP/pect/PDC"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • My main question is, how can I feed a list of strings into file.path? – Pythonner12 Feb 11 '20 at 17:58
  • In case you are interested in the answer, your main question I tried to answer – akrun Feb 11 '20 at 18:10
  • Thanks! I was looking for do.call My question wasn't very well worded, what I was looking for was a way to unpack arguments from a list like in python. I found a similar question/response here on stack overflow: https://stackoverflow.com/questions/3414078/unpacking-argument-lists-for-ellipsis-in-r – Pythonner12 Feb 12 '20 at 09:55
  • 1
    In `R`, there is no `*` or `**` for that purpose – akrun Feb 12 '20 at 15:24
1

With an array being passed as the input it is applying the function to each element separately. It might be necessary to use paste with the array.

paste(parent_dir, collapse = "/")

Another approach that may be simpler:

dirname(getwd())

The reason that strsplit returns a list is that it can handle multiple inputs:

 users <- c("c:/users/A", "c:/users/B")
 strsplit(users, "/")

[[1]]
[1] "c:"    "users" "A"    

[[2]]
[1] "c:"    "users" "B"

For the environment, dir is a character array with eight elements.

manotheshark
  • 4,297
  • 17
  • 30