Pythonner12
Pythonner12

Reputation: 123

Passing list of characters into file.path in R

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?

Upvotes: 3

Views: 736

Answers (2)

akrun
akrun

Reputation: 887108

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"

Upvotes: 1

manotheshark
manotheshark

Reputation: 4357

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.

Upvotes: 1

Related Questions