6.
Exporting data to various file formats
Exporting data to a text file
# Loading mtcars data
data=read.csv("mtcars.csv")
data
# Write data to txt file: tab separated values sep = "\t"
write.table(mtcars, file = "mtcars.txt", sep = "\t",row.names = TRUE, col.names = NA)
Exporting data to a text file using write.table()
One of the important formats to store a file is in a text file. R provides various methods that
one can export data to a text file.
write.table(): The R base function write.table() can be used to export a data frame or a matrix
to a text file.
Syntax: write.table(x, file, append = FALSE, sep = ” “, dec = “.”, row.names = TRUE,
col.names = TRUE)
# Creating a dataframe
df = data.frame(
"Name" = c("Amiya", "Raj", "Asish"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45)
# Export a data frame to a text file using write.table()
write.table(df,
file = "myDataFrame.txt",
sep = "\t",
row.names = TRUE,
col.names = NA)
Exporting data to a csv file using write.table()
Another popular format to store a file is in a csv(comma-separated value) format. R provides
various methods that one can export data to a csv file.
write.table(): The R base function write.table() can also be used to export a data frame or a
matrix to a csv file.
Syntax: write.table(x, file, append = FALSE, sep = ” “, dec = “.”, row.names = TRUE,
col.names = TRUE)
# Creating a dataframe
df = data.frame(
"Name" = c("Amiya", "Raj", "Asish"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45)
)
# Export a data frame to a text file using write.table()
write.table(df,
file = "myDataFrame.csv",
sep = "\t",
row.names = FALSE,
)
Exporting data to a csv file using write.csv()
write.csv(): This method is recommendable for exporting data to a csv file. It uses “.” for
the decimal point and a comma (“, ”) for the separator.
# Creating a dataframe
df = data.frame(
"Name" = c("Amiya", "Raj", "Asish"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45)
)
write.csv(df, file = "my_data.csv")
Exporting a data file using write.csv2()
write.csv2(): This method is much similar as write.csv() but it uses a comma (“, ”) for the
decimal point and a semicolon (“;”) for the separator.
# Creating a dataframe
df = data.frame(
"Name" = c("Amiya", "Raj", "Asish"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45)
write.csv2(df, file = "my_data.csv")