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:
fileis the path to your CSV file.headertells if the first row has column names (default is TRUE).sepis the separator character, usually a comma.stringsAsFactorscontrols 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
headersetting leading to wrong column names. - Not setting
stringsAsFactors = FALSEwhich 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
| Parameter | Description | Default |
|---|---|---|
| file | Path to the CSV file | Required |
| header | Whether first row is column names | TRUE |
| sep | Field separator character | , |
| stringsAsFactors | Convert strings to factors | FALSE 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.