Files and import/export

Start with the expanded example for each command. Open the variants for options and alternative R approaches. Read the qualifications before adapting the code.

changeeol

Normalize a text file to Unix newlines

Stata

changeeol source.txt destination.txt, eol(unix)

R Package:base

writeBin(charToRaw(paste0(paste(readLines(src),collapse='\n'),'\n')),dst)

Fixed workflow example; adapt the object and column names together.

Write text using explicit Windows CRLF bytes

Stata

changeeol source.txt destination.txt, eol(windows)

R Package:base

writeBin(charToRaw(paste0(paste(readLines(src),collapse='\r\n'),'\r\n')),dst)

Fixed workflow example; adapt the object and column names together.

checksum

Compute a file integrity digest

Stata

checksum sample.txt

R Package:tools

tools::md5sum(src)

MD5 is a workflow alternative: Stata checksum uses POSIX CRC, so digest values are not comparable.

Save a file digest in a sidecar text file

Stata

checksum sample.txt, saving(sample.sum)

R Package:tools

digest <- tools::md5sum(src); writeLines(unname(digest),dst)

Writes an R MD5 sidecar, not a Stata .sum file; Stata cannot validate this format as its CRC sidecar.

copy

Copy a local file to a new path

Stata

copy source.txt destination.txt

R Package:base

file.copy(src,dst,overwrite=FALSE)

src and dst are temporary paths in this runnable fixture; no network transfer is involved.

Overwrite a destination file with a local copy

Stata

copy source.txt destination.txt, replace

R Package:base

file.copy(src,dst,overwrite=TRUE)

Demonstrates overwrite on newly created temporary files only.

dir

List CSV files in a directory

Stata

dir "*.csv"

R Package:base

list.files(path,pattern='[.]csv$',full.names=FALSE)

Fixed workflow example; adapt the object and column names together.

1 more examples and alternatives

List files including hidden dot files

Stata

dir, all

R Package:base

list.files(path,all.files=TRUE,no..=TRUE)

Differs from Stata R all.files includes dot files; hidden-file conventions vary by operating system.

export

Export CSV without variable names

Stata

export delimited id x using sample.csv, novarnames replace

R Package:utils

utils::write.table(data[c('id','x')],path,sep=',',row.names=FALSE,col.names=FALSE,quote=FALSE,na='')
5 more examples and alternatives

Export selected columns to CSV

Stata

export delimited id x using sample.csv, replace

R Package:utils

utils::write.csv(data[c('id','x')],path,row.names=FALSE,na='')

Export a tab-separated table

Stata

export delimited id x using sample.tsv, delimiters("\t") replace

R Package:utils

utils::write.table(data[c('id','x')],path,sep='\t',row.names=FALSE,quote=FALSE,na='')

Export selected columns to an Excel workbook

Stata

export excel id x using sample.xlsx, firstrow(variables) replace

R Package:writexl

writexl::write_xlsx(data[c('id','x')],path)

Export data in SAS XPORT version 5 format

Stata

export sasxport5 sample.xpt, replace

R Package:haven

haven::write_xpt(data,path,version=5,name='SAMPLE')

Fixed workflow example; adapt the object and column names together.

Export labelled values to an SPSS system file

Stata

export spss using sample.sav, replace

R Package:haven

haven::write_sav(data,path)

Fixed workflow example; adapt the object and column names together.

file

Read one line through a text connection

Stata

file open handle using sample.txt, read text
file read handle line
file close handle

R Package:base

con <- file(src,open='rt',encoding='UTF-8'); line <- readLines(con,n=1); close(con)

Fixed workflow example; adapt the object and column names together.

Write and close a UTF-8 text connection

Stata

file open handle using sample.txt, write text
file write handle "hello" _n
file close handle

R Package:base

con <- file(path,open='wt',encoding='UTF-8'); writeLines('hello',con); close(con)

The example closes its own temporary connection explicitly.

filefilter

Replace literal text throughout a small file

Stata

filefilter source.txt destination.txt, from("old") to("new")

R Package:base

writeLines(gsub('old','new',readLines(src),fixed=TRUE),dst,useBytes=TRUE)

Differs from Stata Line-oriented small-file workflow; binary patterns and large-file streaming are not covered.

Replace tab separators in a text file

Stata

filefilter source.txt destination.txt, from(\t) to(";")

R Package:base

writeLines(gsub('\t',';',readLines(src),fixed=TRUE),dst,useBytes=TRUE)

Differs from Stata Literal small-text-file replacement; quoted delimiters in tabular data need a parser instead.

findfile

Find a named file inside a specified directory

Stata

findfile sample.txt, path(folder)

R Package:base

found <- list.files(folder,pattern='^sample[.]txt$',full.names=TRUE); stopifnot(length(found)==1L); normalizePath(found,winslash='/')

Fixed workflow example; adapt the object and column names together.

hexdump

Inspect a file as hexadecimal byte values

Stata

hexdump sample.bin

R Package:base

bytes <- readBin(src,'raw',n=file.info(src)$size); format(bytes)

Fixed workflow example; adapt the object and column names together.

Count byte values in a binary file

Stata

hexdump sample.bin, analyze tabulate

R Package:base

table(as.integer(readBin(src,'raw',n=file.info(src)$size)))

Fixed workflow example; adapt the object and column names together.

import

Import a CSV file with a header

Stata

import delimited using sample.csv, clear

R Package:utils

data <- utils::read.csv(path,stringsAsFactors=FALSE)

Fixed workflow example; adapt the object and column names together.

10 more examples and alternatives

Read a selected range of text rows

Stata

import delimited using sample.csv, rowrange(3:4) varnames(nonames) clear

R Package:utils

data <- utils::read.csv(path,header=FALSE,skip=2,nrows=2,col.names=c('id','x'))

Differs from Stata Row numbers refer to physical file rows including the header; R column names are fixed in this example.

Preserve zero-padded identifiers during import

Stata

import delimited using sample.csv, stringcols(1) clear

R Package:utils

data <- utils::read.csv(path,colClasses=c('character','numeric'))

Fixed workflow example; adapt the object and column names together.

Import a CSV file without a header

Stata

import delimited using sample.csv, varnames(nonames) clear

R Package:utils

data <- utils::read.csv(path,header=FALSE,col.names=c('id','x'))

Differs from Stata R column names id and x are supplied explicitly; Stata would choose default names without further renaming.

Import tab-separated values

Stata

import delimited using sample.tsv, delimiters("\t") clear

R Package:utils

data <- utils::read.delim(path,stringsAsFactors=FALSE)

Fixed workflow example; adapt the object and column names together.

List worksheet names before importing

Stata

import excel using sample.xlsx, describe

R Package:readxl

readxl::excel_sheets(path)

Fixed workflow example; adapt the object and column names together.

Import a bounded Excel cell rectangle

Stata

import excel using sample.xlsx, sheet("Survey") cellrange(A1:B2) firstrow clear

R Package:readxl

data <- readxl::read_excel(path,sheet='Survey',range='A1:B2')

Fixed workflow example; adapt the object and column names together.

Read one named Excel worksheet

Stata

import excel using sample.xlsx, sheet("Survey") firstrow clear

R Package:readxl

data <- readxl::read_excel(path,sheet='Survey')

Fixed workflow example; adapt the object and column names together.

Import a SAS XPORT version 5 file

Stata

import sasxport5 sample.xpt, clear

R Package:haven

data <- haven::read_xpt(path)

Fixed workflow example; adapt the object and column names together.

Import an SPSS system file

Stata

import spss using sample.sav, clear

R Package:haven

data <- haven::read_sav(path)

Fixed workflow example; adapt the object and column names together.

Recognize blank and period missing markers on import

Stata

import delimited using sample.csv, clear

R Package:utils

data <- utils::read.csv(path,na.strings=c('','.'),stringsAsFactors=FALSE)

Fixed workflow example; adapt the object and column names together.

infile

Import whitespace-separated numeric fields

Stata

infile id x using sample.txt, clear

R Package:utils

data <- utils::read.table(path,col.names=c('id','x'),header=FALSE)

Free-format example with simple unquoted numeric fields.

Import quoted text and numeric fields

Stata

infile str8 name x using sample.txt, clear

R Package:utils

data <- utils::read.table(path,col.names=c('name','x'),header=FALSE,stringsAsFactors=FALSE)

infix

Read adjacent fixed-width numeric fields

Stata

infix id 1-2 x 3-5 using sample.txt, clear

R Package:utils

data <- utils::read.fwf(path,widths=c(2,3),col.names=c('id','x'))

Read fixed-width fields while skipping a spacer

Stata

infix str3 code 1-3 x 5-6 using sample.txt, clear

R Package:utils

data <- utils::read.fwf(path,widths=c(3,-1,2),col.names=c('code','x'),stringsAsFactors=FALSE)

jdbc

Append controlled rows to an existing SQL table

Stata

jdbc insert id score, table("people")

R Package:DBI

DBI::dbAppendTable(con,'people',data); observed <- DBI::dbReadTable(con,'people'); DBI::dbDisconnect(con)

Requires an existing Stata DSN/JDBC connection for the shown Stata example. The controlled SQLite fixture verifies the SQL/table operation, not ODBC/JDBC driver connection; use an appropriate DBI backend in production.

Load an entire SQL table through a DBI backend

Stata

jdbc load, table("people")

R Package:DBI

data <- DBI::dbReadTable(con,'people'); DBI::dbDisconnect(con)

Requires an existing Stata DSN/JDBC connection for the shown Stata example. The controlled SQLite fixture verifies the SQL/table operation, not ODBC/JDBC driver connection; use an appropriate DBI backend in production.

mkdir

Create a directory

Stata

mkdir work

R Package:base

dir.create(path)

The runnable fixture creates a new directory under R’s temporary directory.

odbc

Inspect database table field names

Stata

odbc describe "people", dsn("research")

R Package:DBI

fields <- DBI::dbListFields(con,'people'); DBI::dbDisconnect(con)

Requires an existing Stata DSN/JDBC connection for the shown Stata example. The controlled SQLite fixture verifies the SQL/table operation, not ODBC/JDBC driver connection; use an appropriate DBI backend in production. This row returns names only, not the Stata column-type report.

Load selected rows from a SQL query

Stata

odbc load, exec("SELECT id, score FROM people WHERE score >= 20") dsn("research")

R Package:DBI

data <- DBI::dbGetQuery(con,'SELECT id, score FROM people WHERE score >= 20 ORDER BY id'); DBI::dbDisconnect(con)

Requires an existing Stata DSN/JDBC connection for the shown Stata example. The controlled SQLite fixture verifies the SQL/table operation, not ODBC/JDBC driver connection; use an appropriate DBI backend in production.

Inspect available tables in a database

Stata

odbc query "research"

R Package:DBI

tables <- DBI::dbListTables(con); DBI::dbDisconnect(con)

Requires an existing Stata DSN/JDBC connection for the shown Stata example. The controlled SQLite fixture verifies the SQL/table operation, not ODBC/JDBC driver connection; use an appropriate DBI backend in production.

outfile

Export comma-separated fields without a header

Stata

outfile id x using sample.csv, comma replace

R Package:utils

utils::write.table(data[c('id','x')],path,sep=',',row.names=FALSE,col.names=FALSE,quote=FALSE,na='.')

Export plain numeric fields with Stata-style missing text

Stata

outfile id x using sample.txt, replace

R Package:utils

utils::write.table(data[c('id','x')],path,sep=' ',row.names=FALSE,col.names=FALSE,quote=FALSE,na='.')

save

Save a table as a current Stata DTA file

Stata

save sample.dta, replace

R Package:haven

haven::write_dta(data,path)

Differs from Stata R object names are not stored as Stata’s active-data state; haven writes supported Stata metadata.

saveold

Write a Stata 12-compatible DTA file

Stata

saveold sample.dta, version(12) replace

R Package:haven

haven::write_dta(data,path,version=12)

Differs from Stata Use names accepted by haven’s older-format validation; this fixture uses names of at least two characters.

savespss

Save the data as an SPSS file

Stata

savespss "data.sav", replace

R Package:haven

haven::write_sav(data, path)

Differs from Stata Community command. haven writes variable and value labels, but rejects Stata tagged missing values (.a, .b) with an error. Convert them explicitly to ordinary NA or to chosen SPSS user-missing codes with haven::labelled_spss() before writing. String widths and display formats may differ.

setroot

Locate a project root from a marker file

Stata

setroot

R Package:rprojroot

root <- rprojroot::find_root(rprojroot::has_file('.here'),path=child)

Uses the explicit .here marker and a supplied starting path; the Stata command also supports other markers and stores a global macro.

type

Read lines from a UTF-8 text file

Stata

type sample.txt

R Package:base

readLines(src,encoding='UTF-8')

Differs from Stata Returns text lines; print or cat them for a console display.

Read only the beginning of a text file

Stata

type sample.txt, lines(1)

R Package:base

readLines(src,n=1,encoding='UTF-8')

Fixed workflow example; adapt the object and column names together.

unicode

Convert a Latin-1 text file to UTF-8

Stata

unicode convertfile source.txt destination.txt, srcencoding("latin1") dstencoding("utf-8")

R Package:base

text <- readLines(src,encoding='latin1'); writeBin(charToRaw(paste0(iconv(text,from='latin1',to='UTF-8'),'\n')),dst)

Fixed workflow example; adapt the object and column names together.

unzipfile

Extract a ZIP archive into a chosen temporary directory

Stata

unzipfile sample.zip

R Package:utils

utils::unzip(archive,exdir=destination)

Differs from Stata R extraction directory is explicit; Stata defaults to the current working directory.

use

Read selected columns from a DTA file

Stata

use id x using sample.dta, clear

R Package:haven

data <- haven::read_dta(path,col_select=c('id','x'))
1 more examples and alternatives

Read the first observations from a DTA file

Stata

use sample.dta in 1/3, clear

R Package:haven

data <- haven::read_dta(path,n_max=3)

Fixed workflow example; adapt the object and column names together.

zipfile

Create a ZIP archive containing a text file

Stata

zipfile sample.txt, saving(sample.zip)

R Package:zip

zip::zipr(archive,src)

Fixed workflow example; adapt the object and column names together.