R Load CSV File as data.table (2 Examples)

In this post, you’ll learn loading a CSV file as a data.table and saving a data.table as a CSV file in R programming.

Setting up the Examples

Install and load the data.table package.

install.packages("data.table")                   # Install & load data.table package
library("data.table")

We use the iris dataset to illustrate the file saving and loading.

data(iris)                                       # Loading iris data set
head(iris)                                       # Printing head of data
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

Define object iris_dt, which is the data.table version of the iris data.

iris_dt <- data.table(data.table::copy(iris))    # Copying data as data.table

Set a path to a folder of your choice. We use this folder to store the example data in.

path <- "C:/Users/..."                           # Setting a path to the folder where you want to save the data to

Example 1: Exporting a data.table as a CSV File

We can export the data iris_dt as a CSV file with the following command.

?write.csv
write.csv(iris_dt,                               # Saving data as CSV file
         file = paste0(path, "iris_csv.csv"))

For the different options of function write.csv(), take a look at the documentation, which you can open with ?write.csv. For example, the arguments allow for changing the decimal symbol.

Example 2: Importing a CSV File as a data.table

In this example, we read a CSV file as a data.table. For that, we first read the file as a data.frame and then convert it to a data.table with the following lines of code. With class(), we check for the class of the object.

iris_imported <- read.csv(file = paste0(path, "iris_csv.csv")) # Reading the data
class(iris_imported)                             # Getting object class
# [1] "data.frame"
setDT(iris_imported)                             # Transforming to data.table
class(iris_imported)                             # Getting object class
# [1] "data.table" "data.frame"

 

Anna-Lena Wölwer R Programming & Survey Statistics

Note: This article was created in collaboration with Anna-Lena Wölwer. Anna-Lena is a researcher and programmer who creates tutorials on statistical methodology as well as on the R programming language. You may find more info about Anna-Lena and her other articles on her profile page.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top