How to start a project folder and write our first R program

It’s time to write the first R program. Follow the steps below to get started.

Learn to set up a project folder for programs and data files

The first step in creating a project is to set up a project folder to hold relevant datasets, programs, and output files. We can think of a project folder as our home mailing address and all the relevant datasets, programs, and output files as the mail and packages to be delivered to us. The packages and mail won’t be delivered to the right place without the mailing address. So, a project folder allows us to easily find all the relevant files and avoid having them mingled and conflated with files for other projects or purposes.

In Windows, we can create a project folder via the following steps: Open My Computer or File Explorer; right-click on the root directory, such as C: or D:; click on New; click on New Folder or Folder; and type in a meaningful name for the new folder, such as Project.

Learn to execute a simple R program

The second step is to learn to write an extremely simple R program and run it. R has a default working directory or folder. We’re interested in directing R to change the current default working directory to the Project folder. It’s like directing our mail to be delivered to our home address, rather than the post office address. The Project folder is where we keep our program and data files. To do so, we first identify the working directory of the current R session and then change it to the Project folder. Finally, we verify that the change is successful. In the program editor, we type the following:

getwd()

The getwd function lists the name of the current working directory. Next, we type the following:

setwd("C:/Project")

The setwd function changes the working directory for the current R session. The function’s argument is inside the parentheses, between double quotation marks, and it employs one forward slash. It specifies the path to the Project folder as the working directory for the current R session. This line of code makes it possible for us to refer to the files within the Project folder without specifying the path again during the remaining R session.

Get hands-on with 1200+ tech skills courses.