0
0
R Programmingprogramming~5 mins

read.table and delimiters in R Programming

Choose your learning style9 modes available
Introduction

We use read.table to load data from files into R. Delimiters tell R how the data columns are separated.

You have a text file with data separated by spaces or tabs.
You want to read a CSV file but need to specify a different delimiter.
You have a file where columns are separated by commas, semicolons, or other characters.
You want to load data into R for analysis or visualization.
Syntax
R Programming
read.table(file, sep = "", header = FALSE, ...)

file is the path to your data file.

sep defines the delimiter between columns. Default is any whitespace.

Examples
Reads a file where columns are separated by spaces or tabs (default).
R Programming
read.table("data.txt")
Reads a CSV file where columns are separated by commas and the first row has column names.
R Programming
read.table("data.csv", sep = ",", header = TRUE)
Reads a file where columns are separated by semicolons.
R Programming
read.table("data_semicolon.txt", sep = ";")
Sample Program

This program reads a small CSV text stored in a string. It uses comma as delimiter and the first row as header. Then it prints the data frame.

R Programming
text <- "Name,Age,City\nAlice,30,New York\nBob,25,Los Angeles"
data <- read.table(textConnection(text), sep = ",", header = TRUE, stringsAsFactors = FALSE)
print(data)
OutputSuccess
Important Notes

If your file uses tabs, you can use sep = "\t".

Set header = TRUE if the first line has column names.

Use read.csv as a shortcut for comma-separated files.

Summary

read.table loads data from text files into R.

The sep argument tells R how columns are separated.

Always check if your file has headers and set header accordingly.