1 Learning Objectives

  • Understand R’s working directory and file paths
  • Import data from CSV files using base R and readr
  • Import data from Excel files using readxl
  • Export data frames back to CSV and Excel
  • Perform an initial inspection of any newly imported dataset

2 The Working Directory

R always reads and writes files relative to a working directory unless you give a full path.

getwd()                        # see current working directory
setwd("C:/Users/YourName/Data") # change it (use your own path)

Best Practice: In RStudio, create an RStudio Project (File > New Project) for each course/assignment. This automatically manages your working directory and keeps files organized — far safer than setwd().

3 Reading CSV Files

CSV (Comma-Separated Values) is the most common format for tabular data.

3.1 Base R Method

students <- read.csv("students.csv", stringsAsFactors = FALSE)

3.2 Using readr (faster, more consistent, tidyverse-style)

# install.packages("readr")
library(readr)
students <- read_csv("students.csv")

readr::read_csv() is generally preferred in modern R because it is faster, gives a helpful column-type summary, and never auto-converts text to factors.

3.3 Simulating This With Built-in Data (for practice)

Since we can’t guarantee a file exists on your machine, let’s create one to practice with:

sample_data <- data.frame(
  name = c("Amina", "Hodan", "Yusuf"),
  score = c(88, 92, 65)
)

write.csv(sample_data, "sample_students.csv", row.names = FALSE)

# Now read it back in
loaded_data <- read.csv("sample_students.csv")
loaded_data
##    name score
## 1 Amina    88
## 2 Hodan    92
## 3 Yusuf    65

4 Reading Excel Files

Base R cannot read .xlsx files directly — we need the readxl package.

# install.packages("readxl")
library(readxl)

excel_data <- read_excel("grades.xlsx")               # first sheet by default
excel_data_sheet2 <- read_excel("grades.xlsx", sheet = 2)
excel_data_named <- read_excel("grades.xlsx", sheet = "Term1")

# List all sheet names in a workbook
excel_sheets("grades.xlsx")

5 Writing/Exporting Data

5.1 Export to CSV

write.csv(sample_data, "output_students.csv", row.names = FALSE)
# row.names = FALSE avoids adding an unwanted extra ID column

5.2 Export to Excel

# install.packages("writexl")
library(writexl)
write_xlsx(sample_data, "output_students.xlsx")

6 Importing Data Using RStudio’s Point-and-Click Interface

RStudio also offers a menu-driven importer:

File > Import Dataset > From Text (base) / From Text (readr) / From Excel

This is a great way to see the code RStudio generates for you (it shows the exact read_csv() call in the console) — a useful way to learn the syntax.

7 First Steps After Importing ANY Dataset

Always run these checks immediately after loading new data — this habit will save you hours of debugging later:

str(loaded_data)        # types of each column
## 'data.frame':    3 obs. of  2 variables:
##  $ name : chr  "Amina" "Hodan" "Yusuf"
##  $ score: int  88 92 65
head(loaded_data)       # first 6 rows
##    name score
## 1 Amina    88
## 2 Hodan    92
## 3 Yusuf    65
dim(loaded_data)        # rows and columns
## [1] 3 2
summary(loaded_data)    # quick stats per column
##      name               score      
##  Length:3           Min.   :65.00  
##  Class :character   1st Qu.:76.50  
##  Mode  :character   Median :88.00  
##                     Mean   :81.67  
##                     3rd Qu.:90.00  
##                     Max.   :92.00
colSums(is.na(loaded_data))  # count missing values per column
##  name score 
##     0     0

8 Common Import Problems and Fixes

Problem Likely Cause Fix
All columns read as text Wrong delimiter or encoding Check sep = ";" or sep = "\t"
Numbers read as character Commas used as decimal points read.csv(..., dec = ",")
Strange symbols in text Wrong file encoding read.csv(..., fileEncoding = "UTF-8")
Missing values not recognized Uses a custom code like "N/A", "-" read.csv(..., na.strings = c("N/A", "-"))
Extra blank rows/columns Excel file has formatting artifacts Use readxl::read_excel(), then na.omit() or manual cleaning

9 Worked Example

Scenario: You export a small gradebook, then re-import and validate it, simulating a real workflow.

gradebook <- data.frame(
  student_id = 1:4,
  name = c("Ali", "Sara", "Deka", "Omar"),
  midterm = c(70, 85, 60, 92),
  final = c(75, 88, 55, 95)
)

write.csv(gradebook, "gradebook.csv", row.names = FALSE)

gradebook_check <- read.csv("gradebook.csv")
identical(gradebook, gradebook_check)   # sanity check: did the round trip preserve the data?
## [1] FALSE
str(gradebook_check)
## 'data.frame':    4 obs. of  4 variables:
##  $ student_id: int  1 2 3 4
##  $ name      : chr  "Ali" "Sara" "Deka" "Omar"
##  $ midterm   : int  70 85 60 92
##  $ final     : int  75 88 55 95

10 Practice Exercises

  1. Create a small data frame with at least 3 columns and 5 rows about any topic you like (e.g., favorite foods, movies, football teams).
  2. Export it to a CSV file using write.csv().
  3. Read the CSV back into a new object and confirm it looks correct with head().
  4. Add a “fake” missing value manually to one cell, re-save the CSV, and use colSums(is.na(...)) to detect it after re-importing.
  5. Install readxl and writexl, then export your data frame to an .xlsx file and read it back.
  6. Deliberately try read.csv() on a file that doesn’t exist. What error message does R give you?
  7. Explain, in your own words, the difference between getwd() and setwd().
  8. Why is row.names = FALSE recommended when writing CSVs?

11 Quiz

Q1. Which package provides read_excel() for importing .xlsx files?

  1. readr
  2. readxl
  3. dplyr
  4. Base R already supports this natively

Q2. What does getwd() do? a) Sets a new working directory b) Gets the current working directory c) Gets the Windows Desktop path d) Deletes the working directory

Q3. Why might you specify na.strings = c("N/A", "-") when reading a CSV?

  1. To rename columns
  2. To tell R which text values should be treated as missing data
  3. To skip the first row
  4. To convert numbers to characters

Q4. What function quickly shows you the number of missing values in each column of a data frame df?

  1. sum(df)
  2. colSums(is.na(df))
  3. nrow(df)
  4. str(df)

Q5. What argument prevents write.csv() from adding an unwanted row-number column?

  1. header = FALSE
  2. sep = ","
  3. row.names = FALSE
  4. quote = FALSE
Click to reveal Answer Key Q1: b | Q2: b | Q3: b | Q4: b | Q5: c

12 Summary

  • The working directory determines where R looks for/saves files by default; RStudio Projects manage this automatically.
  • read.csv() / readr::read_csv() import CSVs; readxl::read_excel() imports Excel files.
  • write.csv() and writexl::write_xlsx() export data back out.
  • Always inspect newly imported data with str(), head(), summary(), and a missing-value check.

Next Lesson: Data Cleaning and Manipulation Basics.