Skip to Main Content

Intro to R Programming

R is a powerful tool for data analysis and visualization; this guide will provide resources to get you started with this programming language!

Import Data from a File

Oftentimes, you would import data into R from a previously saved file.

Importing data files using the Script Editor:

When importing data into R, save it as an object and give it a name using the <- assignment operator.

To import a tab delimited file, write the code: tab_data <- read.table("filelocation/Intro To R/datafile.txt", sep = "")

  • Be sure the file directory path is a forward slash (/), NOT a back slash (\).

To import a comma delimited file, write the code: csv_data <- read.csv("filelocation/Intro To R/datafile.csv", sep = ",")

  • Note that the argument sep= may not be necessary as R knows the separators are commas in .csv files and blank spaces in .txt files, but sometimes R won’t read the data correctly unless you specify the separator.

Codes for other file types and functions/packages to ‘read’ in the data, ordered by usage popularity:

Type of Data File Extension R Code/Packages
Tabular data .CSV read_csv() function from the readr package
Tabular data .TSV read.table() function from the readr package
Text .TXT

readLines() function

OR  read_lines() function from the readr package

Excel .XLSX read.xlsx() from the xlsx package
Google sheets Google URL or Sheet ID read_sheet() from the googlesheets4 package
SPSS statistical program file .SAS7BDAT or .SAS7BCAT read_sas() from the haven package
SAS statistical program file .SAV read_sav() from the haven package
Stata statistical program file .DTA read_dta() from the haven package
MySQL database MySQL database files dbConnect() from the RMySQL package
Fixed-width text file .TXT read.fwf() from the utils package

Importing data files using RStudio functions:

To load data into Posit Cloud, first upload the data set in the ‘Files’ pane. Upload the file into your ‘cloud/project’ folder.

In RStudio, click ‘Import Dataset’ in the top right Environment pane in your working session. Select options to import from Text, Excel, SPSS, SAS, or Stata files. Assign a short descriptive 'Name' to the data set.