How to Export DataFrame to CSV in R

You can use the write.csv() from base R or write_csv() from “readr” package to export a dataframe to CSV in R.

write.csv()

write.csv(df_1,”csv_file_name.csv”, row.names=FALSE)

write_csv()

write_csv(df_2,”csv_file_name.csv”)

Example 1: Use write.csv()

# Step 1: Generate the Data Frame 
df_1 <- data.frame(Letters=c('A', 'B', 'C', 'D', 'E'),
                 Numbers=rbinom(5, 1, 0.85))

# view the data frame
print(df_1)

# Steps 2: Use write.csv() function to save the Data Frame as a CSV file in R
write.csv(df_1,"df_1.csv", row.names=FALSE)

The following is the output of the dataframe df_1.

> print(df_1)
  Letters Numbers
1       A       1
2       B       1
3       C       0
4       D       1
5       E       0

Example 2: Use write_csv()

# Step 1: Generate the Data Frame and print out the Data Frame
df_2 <- data.frame(Letters=c('A', 'B', 'C', 'D', 'E'),
                   Numbers=floor(runif(5, min=0, max=23)))

# view the data frame
print(df_2)

# use the R package "readr"
library(readr)

# Steps 2: Use write_csv() function to save the Data Frame as a CSV file in R
write_csv(df_2,"df_2.csv")

The following is the output of the dataframe df_2.

> print(df_2)
  Letters Numbers
1       A       1
2       B       2
3       C       8
4       D      18
5       E       6

Leave a Comment