How to read and write STATA .dta files in R or import data from and export data to STATA .dta files, using read_stata() (haven), and write_dta() (haven).

Below are the functions and the package you need to install.

Packages and Functions for Reading and Writing STATA or .dta Files in R
Activity Package Function
Read STATA .dta haven read_stata()
Write STATA .dta haven write_dta()

1 Read or Import Data from STATA Files in R

Download testdata.dta file.

The STATA or .dta file format is a proprietary binary file format designed for datasets with Stata.

To read or import STATA or .dta files in R, install the "haven" package:

install.packages("haven")

Then load the package with the following:

library("haven")

After the installation and loading of the package, if you set or have the working directory as the folder containing the file, you can read or import the STATA or .dta file with the following line of code:

read_stata("testdata.dta")

Or specify the full path of where the file is located:

read_stata("C:/Users/Public/Statscodes/Rdata/read-files/testdata.dta")
STATA File Read in R

STATA File Read in R

To remove the initial messages, you can turn the STATA input to a dataframe as below:

data.frame(read_stata("testdata.dta"))
Image 2 of STATA File Read in R

Image 2 of STATA File Read in R

2 Write or Export Data to STATA Files in R

The dataframe named dtfrm will be used:

dtfrm = data.frame(Group = c("A", "B", "B", "C", "D"), 
                   ID = c("A02", "B12", "B15", "C04", "D07"), 
                   Score = c(9, 8, 8, 10, 7), 
                   Position = c(2, 3, 3, 1, 5))
dtfrm
  Group  ID Score Position
1     A A02     9        2
2     B B12     8        3
3     B B15     8        3
4     C C04    10        1
5     D D07     7        5

To write or export data to STATA or .dta files in R, first install the "haven" package:

install.packages("haven")

Then load the package with the following:

library("haven")

After the installation and loading of the "haven" package, you can save the STATA or .dta file to the working directory with the following line of code:

write_dta(dtfrm, "outdata.dta")

Or specify the full path of where you want to save the file:

write_dta(dtfrm, "C:/Users/Public/Statscodes/Rdata/write-files/outdata.dta")

The STATA file should look like this reloaded in R:

STATA File Written and Reloaded in R

STATA File Written and Reloaded in R

Copyright © 2020 - 2024. All Rights Reserved by Stats Codes