How can I use the fwrite function in R?

The fwrite function in R is used to write data frames or matrices to a file. It allows for efficient and fast writing of large data sets to a file in a specified format. To use the fwrite function, the user must first specify the data frame or matrix to be written, the file path, and the desired format. An example of using the fwrite function is as follows:

fwrite(data = my_data, file = “C:/Users/username/Documents/my_data.csv”, format = “csv”)

This command will write the data frame “my_data” to a CSV file located at the specified file path. The function can also be customized to include additional parameters such as column names and row names. Overall, the fwrite function is a useful tool for efficiently exporting data from R to a file in a desired format.

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:UsersbobDesktopdata.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:UsersbobDesktopdata.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