Azad Rasul
SmartRS

SmartRS

6- Working directories and paths in R programming

Azad Rasul's photo
Azad Rasul

Published on Jul 17, 2021

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Set a default working directory in RStudio

Tools> Global Options> General> Default working directory (when not in a project)> Browse> Choose your directory> Apply> OK

Default_working_directory.png

Default_working_directory2.png

Get current dierectory

getwd() # stands for "get working directory"

Change working directory

setwd("D:/R4Researchers")# setwd() function stands forset working directorysetwd('C:/Users/Azad/Downloads') # Change working directory to download folder
getwd()

Choose directory from RStudio:

ctrl+shift+H or: Session> Set Working directories> Choose Directory

List functions

ls() # ls() function shows defined data sets and functions

ls().png

To remove everything in the working environment (only apply it when it is necessary):

rm(list=ls())

Select path:

file.path('D:', 'Natural_Resources', 'Soil')
file.path('D:', 'R4Researchers', 'India_China_LAI_and_LST.csv')

Use path for set directory

setwd(file.path('D:', 'Natural_Resources', 'Soil'))
getwd()

An absolute path

dt<- read.csv('D:/R4Researchers/data_ziped/data_ziped.csv')
dt

Relative path

dt1<- read.csv('./data_ziped/data_ziped.csv')

Create folder and files

Create a folder inside the working directory:

dir.create('data')
dir.create('data/test')

Create an empty file inside the directory:

file.create("test_text_file.txt")
file.create("test_word_file.docx")
file.create("test_csv_file.csv")

Create 10 empty csv file inside directory using sapply function

sapply(paste0("test", 1:10, ".csv"), file.create)

Delete file

unlink('test_word_file.docx')
file.remove('test_text_file.txt')

Delete 5 files with sapply function

sapply(paste0('test', 1:5, '.csv'), unlink)

Copy file

# file.copy("name_file.csv", "destination_folder")
file.copy("test5.csv", "D:/R4Researchers/data/test")

List files in the directory

list.files("D:/R4Researchers/", full.names = TRUE, recursive = TRUE)
# list all CSV files non-recursively
list.files(pattern = ".csv")

# list all CSV files recursively through each sub-folder
list.files(pattern = ".csv", recursive = TRUE)

Check if a file or directory exists

file.exists("D:/R4Researchers/data/test")
# TRUE
file.exists("D:/R4Researchers/data/test.csv")
# FALSE
file.exists('D:/R4Researchers/data')
# TRUE 
dir.exists('D:/R4Researchers')
# TRUE
dir.exists('D:/R4Researchers/new_data')
# FALSE

Did you find this article valuable?

Support Azad Rasul by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this
Proudly part of