- Relational Operators in R
- Logical Operators in R
- Conditional Statements in R
- For Loop in R Programming
- While and Repeat Loop in R Programming
- Functions in R Programming
- Creating Functions in R
- Apply Functions in R
- Importing Data from External Data Sources in R
- Importing Data Using read.csv in R
- Import Data using read.table in R
- Importing Data Using data.table – fread in R
- Importing Data from Excel in R
- Using XLConnect in R Programming
- Importing Data from a Database in R
- SQL Queries from R
- Importing Data from Web in R
Import Data using read.table in R
We learnt that we can use
read.csv() function to import data from files in comma separated values (CSV) format. A data table can reside in a text file where the cells inside the table are separated by blank characters. If your data uses another character to separate the fields, not a comma, R also has the more general
So if your separator is a tab, for instance, this would work:
mydata <- read.table("filename.txt", sep="\t", header=TRUE)
The command above also indicates there's a header row in the file with
If, say, your separator is a character such as | you would change the separator part of the command to sep="|".
Categories or values?
Because of R's roots as a statistical tool, when you import non-numerical data, R may assume that character strings are statistical factors -- things like "poor," "average" and "good" -- or "success" and "failure."
But your text columns may not be categories that you want to group and measure, just names of companies or employees. If you don't want your text data to be read in as factors, add
stringsAsFactor=FALSE to read.table, like this:
mydata <- read.table("filename.txt", sep="\t", header=TRUE, stringsAsFactor=FALSE)
This content is for paid members only.
Join our membership for lifelong unlimited access to all our data science learning content and resources.