• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Rstats 101

Learn R Programming Tips & Tricks for Statistics and Data Science

  • Home
  • About
    • Privacy Policy
  • Show Search
Hide Search

How to create a directory if it does not exist in R

rstats101 · July 12, 2022 ·

In this tutorial we will learn how to create a directory if it does not exist already using R. We will be using two base R functions, one of checking if a directory exists and the other for creating a directory. If a directory exists already we would not be creating it and if the directory does not exist, we will create a new directory using the R functions.

Find out if a directory exists or not using dir.exists()

Let us get started with checking if a directory exists or not.

In R, we can use dir.exists() function to check if a directory exists or not. dir.exists() will return TRUE if the directory exists and FALSE otherwise.

Let us check for a director named “output” exists or not at the current working directory. Also assume that the directory “output” does not exist. Therefore when we use dir.exists(), we would get FALSE

dir.exists("output")

## [1] FALSE

Create a directory using dir.create() in R

Since the directory does not exist let us try to create the director using dir.create() function.

dir.create("output")

Now if we check if the directory exists using dir.exists(), we will get TRUE as answer.

dir.exists("output")

## [1] TRUE

Note that if you try to create a directory that already exists, we would get the following warning

dir.create("output")

Warning in dir.create("output") : 'output' already exists

We can wrap these two functions using if statement to create a directory if it does not exist. As we explained, we will create the directory if does not exist already, otherwise just print the statement that it already exists.

if (!dir.exists("output")){
  dir.create("output")
}else{
  print("dir exists")
}

Related

Filed Under: dir.create(), dir.exists() Tagged With: create a directory if it does not exist in R

Primary Sidebar

Recent Posts

  • How to create a nested dataframe with lists
  • How to compute proportion with tidyverse
  • How to Compute Z-Score of Multiple Columns
  • How to drop unused level of factor variable in R
  • How to compute Z-score

Categories

%in% arrange() as.data.frame as_tibble built-in data R colSums() R cor() in R data.frame dplyr dplyr across() dplyr group_by() dplyr rename() dplyr rowwise() dplyr row_number() dplyr select() dplyr slice_max() dplyr slice_sample() drop_na R duplicated() gsub head() impute with mean values is.element() linear regression matrix() function na.omit R NAs in R near() R openxlsx pivot_longer() prod() R.version replace NA replace NAs tidyverse R Function rstats rstats101 R version scale() sessionInfo() t.test() tidyr tidyselect tidyverse write.xlsx

Copyright © 2025 · Daily Dish Pro on Genesis Framework · WordPress · Log in

Go to mobile version