Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • using foreach to generate mean values of variables

    I have a dataset of microbial counts with each variable being a count of that organism in a faecal sample from a pony identified by variable ponyid. Samples were taken serially on a daily basis for 15 days thus each row represents a sample identified by the variable sampleno which has a value of 1-15. For each microbe - I wish to get the mean of the count from the last 3 days. I have used the following code for a given microbe -"fibrobacter"

    bysort ponyid (sampleno):gen avNfibro= (fibrobacter[_N] + fibrobacter[_N-1] + fibrobacter[_N-2])/3

    this works for the specific variable 'fibrobacter' and produces a column containing one number per pony which is the mean of the last 3 counts

    I wish to use foreach to produce the same variable for each microbe (there are about 100)
    I have tried

    foreach var of varlist fibrobacter- pluralibacter {
    bysort ponyid (sampleno): gen avN`var' = 'var'[_N] +'var' [_N-1] +'var' [_N-3])

    }
    this gives an error message 'var' invalid name (r198)

    I have also tried
    foreach var of varlist fibrobacter- pluralibacter {
    bysort ponyid (sampleno): gen avN`var' = (sum([_N] + [_N-1] + [_N-3]))/

    }
    this runs but gives a variable which is numericallly incorrect

    Help would be gratefully accepted

    Thank you

    Dai Grove-White,
    University of Liverpool

  • #2
    Dai:
    try your code copying and pasting in it:
    Code:
    `var'
    when necessary.
    Kind regards,
    Carlo
    (StataNow 18.5)

    Comment


    • #3
      Your first line of code has the right spirit but the others introduce errors of various kinds.

      Code:
      sort ponyid sampleno
      
      foreach v of varlist  fibrobacter-pluralibacter {
      
          by ponyid:  gen avN`v'= (`v'[_N] + `v'[_N-1] + `v'[_N-2])/3
      
      }

      Comment


      • #4
        It works! Thanks, Nick
        Dai

        Comment

        Working...
        X