Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: RE: reshaping a large number of variables


From   "Nick Cox" <[email protected]>
To   <[email protected]>
Subject   st: RE: reshaping a large number of variables
Date   Sat, 20 Sep 2003 18:16:27 +0100

Radu Ban
>  
> I need a bit of help reshaping a large number of variables. 
> In my dataset I have a lot (>100) variables
> ending in "v1", "v2", or "v3", representing variables for 
> village 1, 2, or 3. Is there a quick way to reshape all 
> these variables from this wide format into a long format, 
> where each observation corresponds to a single village?
>  
> I was thinking to do something along this line:
> *put all variable names in a local macro
> unab mylist : *v1 *v2 *v3 
>  
> *eliminate the trailing number from each name and put new 
> names in a new local macro
> *not sure how to do this
>  
> *reshape using the new local macro
> reshape long `newlist', i(id) j(villagenr)

There is a similar problem at 
http://www.stata.com/support/faqs/data/reshape3.html

Your idea is very good, so long as one constraint is satisfied. 

unab mylist : *v1 

(Note that we don't also want *v2 *v3, as that will 
only produce duplicate stubs in what follows.) 

local mylist : subinstr local mylist "v1" "", all
reshape long `mylist', i(id) j(villagenr) string 

Note the -string- option (as the stubs are "v1", etc.) 

The constraint is that the strings "v1", "v2", 
"v3" must only occur at the end of each variable 
name. 

A more general method, which doesn't assume this, 
is 

foreach v of var *v1 { 
	local mylist "`mylist' `=substr("`v'",1,length("`v'")-2)'" 
} 
reshape long `mylist', i(id) j(villagenr) string 

That -foreach- bit is a contraction of 

foreach v of var *v1 { 
	local nosuffix = substr("`v'",1,length("`v'")-2) 
	local mylist "`mylist' `nosuffix'" 
}   

Nick 
[email protected] 



*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   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