Daeun
Daeun

Reputation: 27

Find directory getting specific file

I want to find directory automatically which is placed with specific file in R.

For example, "/home/R_code/dataloading/abcd.R" is directory and file name. How can I find "/home/R_code/dataloading" with the file names "abcd.R".

Upvotes: 1

Views: 87

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

You could use basename and dirname functions

path <- "/home/R_code/dataloading/abcd.R"
basename(path)
#[1] "abcd.R"

dirname(path)
#[1] "/home/R_code/dataloading"

If you do not know the actual path of the file and just know it's name. We could use list.files with pattern

file_path <- list.files("/home/R_code/", recursive = TRUE, pattern = "abcd.R")
dirname(file_path)

file_path would have the files in "/home/R_code/" directory which has "abcd.R" in their name. Now we can use dirname to get directory name of the files.

Upvotes: 1

Related Questions