How to Use fwrite Function in R (With Example)


You can use the fwrite function from the data.table package in R to export a data frame or matrix to a file.

This function has been shown to be significantly faster than the write.csv function from base R and is recommended when working with large datasets.

This function uses the following basic syntax:

library(data.table)

fwrite(df, file='C:\\Users\\bob\\Desktop\\data.csv', ...)

Note: In order to use the fwrite function, you only need to specify the object name to export and the file location to send it to, but you can refer to the documentation for a complete list of arguments available to use with the fwrite function.

The following step-by-step example shows how to use this function in practice.

Step 1: Create a Data Frame

First, let’s create a data frame in R:

#create data frame
df <- data.frame(var1=c(1, 3, 3, 4, 5),
                 var2=c(7, 7, 8, 3, 2),
                 var3=c(3, 3, 6, 6, 8),
                 var4=c(1, 1, 2, 8, 9))

#view data frame
df

  var1 var2 var3 var4
1    1    7    3    1
2    3    7    3    1
3    3    8    6    2
4    4    3    6    8
5    5    2    8    9

Step 2: Use fwrite() to Write the Data Frame to a File

Next, let’s use the fwrite function from the data.table package to write this data frame to a CSV file called data.csv located on my Desktop:

library(data.table)

#export data frame to Desktop
fwrite(df, file='C:\\Users\\bob\\Desktop\\data.csv')

Step 3: View the Exported File

Next, I can navigate to my Desktop and open the file called data.csv to view the data:

The values in the file match the values from our data frame.

Note that the default delimiter for the fwrite function is a comma, but you can use the sep argument to specify a different delimiter if you’d like.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Use fread() in R to Import Files Faster
How to Export a Data Frame to an Excel File in R
How to Export a Data Frame to a CSV File in R

Leave a Reply

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