The data.table
package introduces the function fread
. While it is similar to read.table
, fread
is usually faster and more flexible, guessing the file's delimiter automatically.
# get the file path of a CSV included in R's utils package
csv_path <- system.file("misc", "exDIF.csv", package = "utils")
# path will vary based on R installation location
csv_path
## [1] "/Library/Frameworks/R.framework/Resources/library/utils/misc/exDIF.csv"
dt <- fread(csv_path)
dt
## Var1 Var2
## 1: 2.70 A
## 2: 3.14 B
## 3: 10.00 A
## 4: -7.00 A
Where argument input
is a string representing:
"filename.csv"
),"grep 'word' filename"
), or"input1, input2 \n A, B \n C, D"
).fread
returns an object of class data.table
that inherits from class data.frame
, suitable for use with the data.table's usage of []
. To return an ordinary data.frame, set the data.table
parameter to FALSE
:
df <- fread(csv_path, data.table = FALSE)
class(df)
## [1] "data.frame"
df
## Var1 Var2
## 1 2.70 A
## 2 3.14 B
## 3 10.00 A
## 4 -7.00 A
fread
does not have all same options as read.table
. One missing argument is na.comment
, which may lead in unwanted behaviors if the source file contains #
.fread
uses only "
for quote
parameter.fread
uses few (5) lines to guess variables types.