How can the fwrite function be used in R, with an example?

The fwrite function in R is used to write data to a file in a specified format. It takes in two main arguments – the data to be written and the file path where it will be written. For example, if we have a dataset called “sales_data” and we want to write it to a CSV file named “sales.csv” in our working directory, we can use the following code: fwrite(sales_data, “sales.csv”). This will write the data to the specified file path in a CSV format, allowing us to easily store and access the data for future use.


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 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

x