Data Export

Below is a comparison of the commands used to write data into various file formats using R, SAS, SPSS and Stata. The variables gender and workshop are categorical factors and q1 to q4, pretest and posttest are considered continuous and normally distributed.

The practice data set is shown here. The programs and the data they use are also available for download here. Examples that are missing for Stata reflect the differences between the two books. We will get around to those when we write the second edition of R for Stata Users.

Writing Comma-Delimited Text Files

R

write.csv(mydata, file="mydataFromR.csv";)

SAS

PROC EXPORT DATA=MYLIB.MYDATA
  OUTFILE="mydataFromSAS.csv"
  DBMS=CSV REPLACE
  PUTNAMES=YES;

SPSS

SAVE TRANSLATE
OUTFILE='mydataFromSPSS.csv'
/TYPE=CSV
/MAP
/REPLACE
/FIELDNAMES
/CELLS=VALUES.

Stata

use mydata,clear
outfile using mydata.csv, comma
type mydata.csv

Writing Tab Delimited Files

R

write.table(mydata,
  file = "mydataFromR.tab",
  quote = FALSE,
  sep = "t",
  na = "",
  row.names = TRUE,
  col.names = TRUE)

# Space delimited:
write.table(mydata, file = "mydataFromR.txt")

SAS

PROC EXPORT DATA=MYLIB.MYDATA
  OUTFILE="mydataFromSAS.txt"
  DBMS=TAB REPLACE;
  PUTNAMES=YES;

SPSS

SAVE TRANSLATE
OUTFILE='mydataFromSPSS.dat'
/TYPE=TAB
/MAP
/REPLACE
/FIELDNAMES
/CELLS=VALUES.

Stata

use mydata,clear
outfile using mydata.tab, tab
type mydata.tab

Writing Excel Files

R

# Do this once:
install.packages("xlsReadWrite")
library("xlsReadWrite")
xls.getshlib()

# Write the file:
library("xlsReadWrite")
write.xls(mydata, file = "mydataFromR.xls")

SAS

PROC EXPORT
DATA=MYDATA
OUTFILE="mydata.xls";
DBMS=EXCELCS LABEL
REPLACE;
SHEET="mydata"

SPSS

SAVE TRANSLATE
OUTFILE='mydataFromSPSS.xls'
/TYPE=XLS
/VERSION=2
/MAP
/REPLACE
/FIELDNAMES.

Writing SAS Files

R

library("foreign")

write.foreign(mydata,
  datafile = "mydataFromR.txt",
  codefile = "mydataFromR.sas",
  package  = "SAS")

Writing SPSS Files

R

library("foreign")

write.foreign(mydata,
  datafile = "mydataFromR.txt",
  codefile = "mydataFromR.sps",
  package  = "SPSS")

Writing Stata Files

R

library("foreign")

write.foreign(mydata,
  datafile="mydata2.csv",
  codefile="mydata2.do",
  package="Stata")

4 thoughts on “Data Export”

  1. Thanks a lot for this nice post. I have juste found out that the package ‘xlsReadWrite’ is not available (for R version 3.2.4). Do you have other alternative to export excel file from R.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.