This is an R Markdown document explaining how to export data from R. There are various ways in which we can export the R out-put (PPT, PDF, HTML) but here we are only concentrating on data types which are in tabuler formats, which we can again use for further processing;
All commands for exporting data, starts with write and after a dot gives further specification like which format it exporting to. The general command we can use to export R data is write.table command, it takes atleast three important arguments “x (the object which has to export)”, “file (the path where we want to save it, with the name of our exporing file)”, “sep (separator: the format in which we want our exported file to be)”.
Note: By default all the exported data files are saved into your documents folder
Lets starts with the general command for exporting data write.table Exporting in text format
test_data001 <- datasets::airquality
write.table(test_data001, file = "~/airquality_dummy.txt", sep = "\t")
Similarly, to Export in comma sep values
test_data002 <- datasets::mtcars
write.table(test_data002, file = "~/mtcars_dummy.csv", sep = ",")
To export data in spreadsheet format we need to take help of package like xlsx or XLConnect.
library(xlsx)
## Loading required package: rJava
## Loading required package: xlsxjars
write.xlsx(test_data001, "D:/test_data001.xlsx")
For other format we can use foreign pack, there are following arguments are essential
df (data frame which you want to export), datafile (Name of file for data output), codefile (Name of file for code output), package = c(“SPSS”, “Stata”, “SAS”)
For SPSS with foreign
library(foreign)
write.foreign(test_data001, "~/test_data001.txt", "~/spss_test_data001.sps", package="SPSS")
For SAS with foreign
write.foreign(test_data001, "~/test_data001.txt", "~/sas_test_data001.sas", package="SAS")
## Some variable names were abbreviated or otherwise altered.
For Stata
write.dta(test_data001, "~/Stata_test_data001.dta")
as we can see there is seperate command for Stata format built under foreign.
That’s the end of our second lesson;enjoy learning R.