# How to work with file system from R

## Temporary directory and files

Firstly let’s create a folder to work with in a temporary directory. Look for details on how to work with temporary files in R in my post When do you need temporary directory and files in R and how to use them.

Function tempfile() does not create any files, it generates a random file name, what is unique for the current R session. By default tempfile() generates file name in R temporary directory.

## Exploring file system

In mydirname variable we have a file path where we can create a file. Now there is nothing. Let’s check it with function file.exists() and the content of the temporary directory with function dir().

## Creating of a directory

Next we really touch our file system and create desired directory.

And check it again:

• existance;
• content of parent directory;
• modification time.

## More listings including R system files

Let’s inspect files from one of installed R-packages. A command system.file() returns full path of files from installed packages. We use it to get a file path of stats package.

Next we list content of this folder.

We can check content of any subdir. For example “demo” folder.

In some situations you would prefer full names:

## Constructing of file names in R

What is a file name? It is a character string. Wrong. It is a system-specific character string.

R function file.path() creates system-specific file names.

Why did file.path() put slashes as separator, when we used to backslash in Windows (for example C:\Program Files\R\R-3.3.1)? There is even a special note on it in file.path’s help page:
The components are by default separated by ‘/’ (not ‘\’) on Windows.