Hotshot
Hotshot

Reputation: 159

How to define a part of a directory path as a variable for further use using R?

I have a little question regarding the script that I would like to write using R. The problem is the following:

I have quite a long script, in which folders are generated and the working directory is set differently several times. And as I'm not the only one, who will be using this script, I would like to write it in a way that everybody only has to change the directory, which is defined as XXX once. This means that USER_1 can use the code as shown below, whereas USER_2 just has to change the definition of XXX.

I tried to do this in the following way:

XXX <- "C:/users/USER_1/Desktop"

setwd(XXX)

path_Folder1 <- "XXX"
new_Folder1 <- "MainFolder/"
dir.create(file.path(dirname(path_Folder1), new_Folder1))

path_Subfolder1 <- "XXX/MainFolder/."
new_Subfolder <- "Subfolder/"
dir.create(file.path(dirname(path_Subfolder1), new_Subfolder))

Setting the working directory as well as the creation of the first folder works perfectly fine. However, for the subfolder I get this error message:

Warning message:
In dir.create(file.path(dirname(path_Subfolder1), new_Subfolder)) :
  cannot create dir 'XXX\MainFolder\Subfolder', reason 'No such file or directory'

Did I miss to add something to this code? Or how would it be possible solve this problem?

Thank you very much for your help already in advance!

Upvotes: 0

Views: 1606

Answers (1)

A. Stam
A. Stam

Reputation: 2222

Something like the following should work:

# Let users change this variable
personal_dir <- "C:/users/USER_1/Desktop"

# Create main folder
main_folder <- "Mainfolder"
main_folder_path <- file.path(personal_dir, main_folder)
dir.create(main_folder_path)

# Create sub folder
sub_folder <- "Subfolder"
sub_folder_path <- file.path(personal_dir, main_folder, sub_folder)
dir.create(sub_folder_path)

I think the reason your code didn't work correctly is that you had the XXX between quotes, i.e. it was processed as a literal string instead of as a pointer to a saved value.

Upvotes: 2

Related Questions