Statalist


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

RE: st: insheet numeric variables as strings


From   Roy Wada <[email protected]>
To   <[email protected]>
Subject   RE: st: insheet numeric variables as strings
Date   Tue, 19 May 2009 23:02:58 -0700

> I am reading a comma delimited file (.txt) to STATA with "insheet",
> but I'd like to make sure some variables are read in as strings, as
> I do not want to lose leading zeros in these variables (ICD-9 
> procedure codes). 
> 
> Alice
 
You can use a modified version of -chewfile- posted here.
 
http://www.stata.com/statalist/archive/2008-08/msg00834.html
 
It's inefficient but does the job.
 
 
*** program here
prog drop _all
*! chewfile version 0.9.1 May2009 by [email protected]
* version 0.9 Aug2008 by [email protected]
program define chewfile
version 8.0
syntax using/, [output(string) first(numlist max=1) last(numlist max=1) clear]
local parse ","
if "`first'"=="" & "`last'"=="" {
 local first 1
 local last .
}
if "`string'"=="string" {
 local str3 "str3"
}
if "`clear'"=="clear" {
 clear
 qui set obs 1
}
if `"`output'"'=="" {
 tempfile dump
 local output `dump'
}

tempname fh outout
local linenum = 0
file open `fh' using `"`using'"', read
qui file open `outout' using `"`output'"', write replace
file read `fh' line
while r(eof)==0 {
local linenum = `linenum' + 1
 if `linenum'==1 | `linenum'>=`first' & `linenum'<=`last' {
 *display %4.0f `linenum' _asis `"`macval(line)'"'
 file write `outout' `"`macval(line)'"' _n
 
 if "`clear'"=="clear" {
  tokenize `"`macval(line)'"', parse(`"`parse'"')
  local num 1
  while "``num''"~="" {
   if `"``num''"'~=`"`parse'"' {
    cap gen str3 var`num'=""
    if _rc~=0 {
     qui set obs `=`=_N'+1'
     cap gen str3 var`num'=""
    }
    cap replace var`num'="``num''" in `linenum'
    if _rc~=0 {
     qui set obs `=`=_N'+1'
     cap replace var`num'="``num''" in `linenum'
    }
   }
   local num=`num'+1
  }
 }
}
file read `fh' line
}
file close `fh'
file close `outout'
end
 

*** creating data
clear
set mem 333m
set obs 100
gen id=_n
forval n=1/200 {
 gen var`n'=uniform()
}
outsheet using test1.txt, replace noname comma
 
 
*** import them as strings:
chewfile using test1.txt, clear
 
 
You can still use output( ), first( ), and last( ) options.
 
 
Roy
 
 
_________________________________________________________________
Windows Live™: Keep your life in sync.
http://windowslive.com/explore?ocid=TXT_TAGLM_BR_life_in_synch_052009
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index