You can use the read.delim() function to read delimited text files into R.
This function uses the following basic syntax:
read.delim(file, header=TRUE, sep=’t’)
where:
- file: The file location.
- header: Whether the first line represents the header of the table. Default is TRUE.
- sep: The table delimiter. Default is tab (t).
The following example shows how to use this function in practice.
Example: How to Use read.delim in R
First, let’s create a data frame in R:
#create data frame df frame(team=c('Mavs', 'Mavs', 'Spurs', 'Nets'), points=c(99, 90, 84, 96), assists=c(22, 19, 16, 20), rebounds=c(30, 39, 42, 26)) #view data frame df team points assists rebounds 1 Mavs 99 22 30 2 Mavs 90 19 39 3 Spurs 84 16 42 4 Nets 96 20 26
Next, let’s use the write.table() function to export the data frame to a tab-delimited text file:
#export to tab-delimited text file write.table(df, 'my_data.txt', quote=FALSE, sep='t', row.names=FALSE)
I can then navigate to the location where I exported the data and view the text file:
I can then use the read.delim() function to read in the text file:
#read in tab-delimited text file my_df delim('my_data.txt') #view data my_df team points assists rebounds 1 Mavs 99 22 30 2 Mavs 90 19 39 3 Spurs 84 16 42 4 Nets 96 20 26
The data frame matches the data frame that we created earlier.
Note that the default table delimiter for the read.delim() function is a tab (t).
Thus, the following code produces the same results:
#read in tab-delimited text file my_df delim('my_data.txt', sep='t') #view data my_df team points assists rebounds 1 Mavs 99 22 30 2 Mavs 90 19 39 3 Spurs 84 16 42 4 Nets 96 20 26
Notes on Using read.delim()
Note that you can use the getwd() function to get the current working directory to find where the first data frame was exported to.
You can also use the setwd() function if you’d like to change the location of the current working directory.
Additional Resources
The following tutorials explain how to import other types of files into R:
How to Manually Enter Raw Data in R
How to Import CSV Files into R
How to Import Excel Files into R (Step-by-Step)