Bookmark and Share

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


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

Re: st: forvalues foreach or while loop for sequential variables


From   Roberto Ferrer <[email protected]>
To   Stata Help <[email protected]>
Subject   Re: st: forvalues foreach or while loop for sequential variables
Date   Thu, 31 Oct 2013 01:42:42 -0430

Robbie,

Here is one way avoiding the loop and using -reshape-.

*-------begin code ---------

clear
set more off

input obs hosp14  hosp15 hosp16
1   1      5    5
2   6      9    6
3   8      1    3
4   5      5    5
5   2      2    2
6   2      9    1
7   1      1    1
8   3      1    7
9   3      0    4
end

list

* Reshape to manipulate
reshape long hosp, i(obs) j(hnum)

sort obs hosp hnum // important
gen hosp2 = hosp
by obs: replace hosp2 = . if hosp[_n] == hosp[_n-1]

drop hosp
rename hosp2 hosp

* Take back to original form
reshape wide hosp, i(obs) j(hnum)
list // compare this with original input

*------- end code ---------

On Thu, Oct 31, 2013 at 12:41 AM, Robbie Katz <[email protected]> wrote:
> I have a wide format data with variables with same text and different
> numbers attached to them. The variables look like this: hospital1
> hospital2 hospital3...hospital15. I want only unique values across
> these variable for any one observation. For instance if both hospital
> 15 and hospital14 have the same value say, 10, then I want to delete
> 10 and replace it with "." for hospital15. Please let me know how I
> can run a loop to achieve this.
>
> I tried the following but it didn't work:
> forvalues num=2/15 {
>           replace hospital`num'=. if hospital`num'==hospital``num'-1'
>   }
>
> Please help,
> Thanks!
> *
> *   For searches and help try:
> *   http://www.stata.com/help.cgi?search
> *   http://www.stata.com/support/faqs/resources/statalist-faq/
> *   http://www.ats.ucla.edu/stat/stata/
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/


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