• Ekta Aggarwal

Exporting data / writing files from R

Updated: Oct 17

In this tutorial we shall be learning how to export following files from SAS:


Writing a CSV file


To write a csv file in R we use write.csv( ) function.

Syntax:

write.csv(data to be exported, "New file name.csv",...)

write.csv(data,"saving_csv_file.csv",row.names = F)

By default, while saving a CSV file, first column containing rownames gets exported as well. To remove that column we write row.names = F


Writing a txt file


To write a txt file in R we use write.table( ) function.

Syntax:

write.table(data to be exported, "New file name.txt",sep = ...)

write.table(mtcars,"saving_txt_file.txt",sep = ",")

Here we can provide any separator as per our wish eg. " " , "," , ";", "/" etc .


Writing an excel file


Method 1: Using writexl package

To write an excel file in R we use write_xlsx( ) function from library writexl.

install.packages("writexl")
library(writexl)
write_xlsx(mtcars,"saving_mtcars.xlsx")


Exporting multiple sheets in excel file:

Suppose we need to export multiple datasets in multiple tabs, for eg. For exporting mtcars and iris datasets in one single excel but in different tabs, we firstly create a list as follows and then use write_xlsx command.

mysheets = list("mtcars_data" = mtcars,"iris_data" = iris)
write_xlsx(mysheets,"Multiple tabs.xlsx")

Method 2: Using openxlsx package

To write an excel file in R we use write.xlsx( ) function from library openxlsx

install.packages("openxlsx")
library(openxlsx)
write.xlsx(mtcars, 'saving_excel_file.xlsx')

Writing a SAS file


To write a SAS file in R we use write.xlsx( ) function from library foreign

install.packages("foreign")
library(foreign)
write.foreign(mtcars, "saving_sas_file.sas",   package="SAS")

Tags: