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: Duplicate variable only if a previous variable has a certain value


From   Nick Cox <[email protected]>
To   "[email protected]" <[email protected]>
Subject   Re: st: Duplicate variable only if a previous variable has a certain value
Date   Fri, 29 Nov 2013 23:40:03 +0000

The syntax for -generate- always starts

generate newvar = ...

where newvar is a new variable name.

You are expecting Stata to evaluate the expression you give and use it
as the new variable name. For that you need the extra scaffolding of
`=  '

generate `=subinstr(`v',"_w_sub400","corr",1)'  = ...

But this would be more Stataish and easier to read:

qui forval j = 21/164 {

    gen rt`j'corr = rt`j'_w_sub400  if correct`j'int == 0

}

Think: what are the variable elements, what are the constant elements?
And cycle over the variable elements along.

Nick
[email protected]


On 29 November 2013 23:27, David de Jong <[email protected]> wrote:

> I'm trying to duplicate a set of variables (response times for a set
> of trials) so that the original value is reproduced only if the trial
> response was correct (which is indicated by an earlier set of
> variables). If the trial response was incorrect the duplicated
> variable should be missing.
>
> Trials are numbered 21-164. Whether the trial was correct is stored in
> variables correct21int-correct164int (0=correct, 1=incorrect, byte).
> Response times are stored in variables rt21_w_sub400-rt164_w_sub400
> (float).
>
> So, for trial 21, I want to create a new variable called rt21corr that
> is equal to rt21_w_sub400 if correct21int equals 0.
>
> I've tried to do this with the following loop:
>
> qui foreach v of var rt21_w_sub400-rt164_w_sub400 {
> generate subinstr(`v',"_w_sub400","corr",1) = `v' if
> subinstr(subinstr(`v',"_w_sub400","int",1),"rt","correct","1") == 0
> }
>
> In case -substr- wanted all of its constituent parts in quotes I tried this:
>
> qui foreach v of var rt21_w_sub400-rt164_w_sub400 {
> generate subinstr("`v'","_w_sub400","corr",1) = `v' if
> subinstr("subinstr("`v'","_w_sub400","int",1)","rt","correct","1") ==
> 0
> }
>
> Both of these return the error message:
> ( invalid name
>
> Can anyone help me figure out how to make this syntax work, or, if
> there is a more elegant way to do what I hope to do.
*
*   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