0
0
R-programmingHow-ToBeginner · 3 min read

How to Read CSV Files in R: Simple Guide with Examples

In R, you can read a CSV file using the read.csv() function by providing the file path as an argument. This function loads the CSV data into a data frame, which you can then use for analysis.
📐

Syntax

The basic syntax to read a CSV file in R is:

  • read.csv(file, header = TRUE, sep = ",", stringsAsFactors = FALSE)

Here:

  • file is the path to your CSV file.
  • header tells if the first row has column names (default is TRUE).
  • sep is the separator character, usually a comma.
  • stringsAsFactors controls if text columns become factors; setting it to FALSE keeps them as strings.
r
read.csv(file, header = TRUE, sep = ",", stringsAsFactors = FALSE)
💻

Example

This example shows how to read a CSV file named data.csv and print its contents.

r
data <- read.csv("data.csv", header = TRUE, stringsAsFactors = FALSE)
print(data)
Output
Name Age City 1 Alice 30 Paris 2 Bob 25 London 3 Carol 27 Tokyo
⚠️

Common Pitfalls

Common mistakes when reading CSV files include:

  • Wrong file path causing errors.
  • Incorrect header setting leading to wrong column names.
  • Not setting stringsAsFactors = FALSE which can convert text to factors unexpectedly.
  • Using wrong separator if the file is not comma-separated.
r
## Wrong way: missing header and default stringsAsFactors TRUE
wrong_data <- read.csv("data.csv")
str(wrong_data)

## Right way: specify header and stringsAsFactors
correct_data <- read.csv("data.csv", header = TRUE, stringsAsFactors = FALSE)
str(correct_data)
Output
## Output for wrong_data structure shows factors for text columns ## Output for correct_data structure shows character columns for text
📊

Quick Reference

ParameterDescriptionDefault
filePath to the CSV fileRequired
headerWhether first row is column namesTRUE
sepField separator character,
stringsAsFactorsConvert strings to factorsFALSE recommended

Key Takeaways

Use read.csv() with the file path to load CSV data into a data frame.
Set header = TRUE if your CSV has column names in the first row.
Set stringsAsFactors = FALSE to keep text columns as strings.
Check the file path and separator to avoid errors.
Print or inspect the data frame to confirm correct loading.