Load Text Files into R
Load text files, such as Baseball Archive data or Retrosheet data, into R and save it as an R datafile for later access.
In the previous hack, I explain how to load data into R by connecting to a database. If you don’t want to install a database, you don’t have to. This hack explains how to load text files directly into R. Loading the data into R is pretty straightforward, but there are a few tricks. We’ll use the read.csv() command in R to load the data, which loads a comma-delimited text file into an R data frame. (For more information about functions and data frames in R, see “Analyze Baseball with R”
[Hack #32]
.)
R includes several functions for loading text files. Each is similar, but there are differences in the default separators for each one. You must specify a file location and then a field separator, a line separator, a decimal separator, column names, and several other options. They all return a data frame corresponding to the contents of the file, as shown in the following table:
Table 4-3.
|
Function |
Header |
Field separator |
Decimal separator |
|---|---|---|---|
|
|
FALSE |
None |
Period |
|
|
TRUE |
Comma |
Period |
|
|
TRUE |
Semicolon |
Comma |
|
|
TRUE |
Tab |
Period |
|
|
TRUE |
Tab |
Comma |
The Baseball Archive files include a header, are separated by commas, and use periods to indicate decimal points. I use the following read.csv() function. In this example, I assume that the files are in a directory called lahman52-csv
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access