Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

re: st: save list of scalars or locals to file

From   Dan Blanchette <>
Subject   re: st: save list of scalars or locals to file
Date   Mon, 16 Apr 2012 10:35:39 -0400 (EDT)


Would writing it out to a txt file work for you?

tempname scs
file open `scs' using "C:\data\sc_data.txt", text write replace
forvalues x = 1/`sc' {
  file write `scs' `" `: display h`x'' "' _n
file close `scs'

The line:
  file write `scs' `" `: display h`x'' "' _n

is a condensed version of these two lines:

  local temp : display h`x'
  file write `scs' `" `temp' "' _n

You may want to have the scalar values enclosed in double
quotes inside the txt file:

  file write `scs' `""`: display h`x''""' _n

Hope this helps,
Dan Blanchette
Research Programming Services
Carolina Population Center
University of North Carolina

Dear Statalisters,

I'm wondering if there is any fast and easy way to export values stored in Stata memory (here: scalars or locals) to a textfile in specific order.

In my example each local or scalar stores one line of text. The order is relevant and specified by stub and number in scalar or local names I use scalars (h1, h2, h3, ... h`sc'). Local 'sc' stores the maximum scalar number.

I basically have two workarounds both using the data sheet:

1. Data sheet.
set obs `sc'
gen str244 var1 = ""
qui forval x = 1/`sc' {
replace var1 = h`x' if `x' == _n }

Fills scalars into the data sheet line after line. Can be exported via - outfile -.
Limitations: very slow with big `sc'; 244 character limit.

2. Log file and data sheet
This way is due to Daniel Kleins very useful hint to display lists of scalars using macro extended functions: pr scadir
	vers 9.2
	scalar dir `: all scalars `"`0'"''

All displayed scalars are logged and imported to the data sheet:

set linesize 244
log using d:/temp/log.txt, replace text
scadir h*
log close infix str244 var1 1-244 using "D:\temp\log.txt", clear

After import into the data sheet further commands clean the data, extract scalar numbers to sort the lines and scalar text for export via - outfile -.
More steps but in the end much faster than looping like in (1).
Limitations: more error prone than (1), 230+ character limit (depends on scalar/local name length)

Any other suggestions?

Best wishes

Stefan Gawrich

*   For searches and help try:

© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index