Announcement

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

  • Loop for creating matrices from stacked data

    Dear all

    I have stacked data on 53 subjects and for each subject 11 observations, every subject has an id number. I would like to create a matrix for two variables, qrisk and qreturn, for each subject. This should yield 53 11x2 matrices.

    I wrote the following loop but I am stuck with the naming.

    Code:
    foreach i in id {
        mkmat qrisk-qreturn if id==`i', matrix(Q`i')
    }
    The loop does execute but I cannot retreive the matrices. Since the id variable goes from 1 through 53 I assumed the names for the matrices would become Q1 through Q53. However:

    Code:
    matrix list Q1
    says there is no matrix with this name.

    Am I using the wrong loop here?

    Thanks in advance.

    Arthur
    Last edited by Arthur Schiltz; 03 May 2022, 09:41.

  • #2
    -foreach i in id- tells Stata to iterate i over the single string id. Consequently, your code creates a single matrix Qid with values of qrisk-return for all observations in which id == id. Since id == id is always true, that means you are just getting a single matrix Qid containing all observations of qrisk-qreturn.

    What you mean to do is:
    Code:
    levelsof id, local(ids)
    foreach i of local ids {
        mkmat qrisk-qreturn if id == `i', matrix(Q`i')
    }
    That said, are you sure you want to do this? Unless you plan to actually do matrix algebra, there is little use of matrices in Stata. What are you going to do with these matrices?

    Comment


    • #3
      Hi, try something:
      Code:
      levelsof id, local(names)
      
      foreach i of local names {    
          mkmat qrisk qreturn if id==`i', matrix(R`i')
      }

      Comment


      • #4
        Clyde Schechter Daniel PV Thank you both for the quick help, this does exactly what I need!

        I need matrices to run an algorithm that tests inconsistencies with GARP (Revealed Preference).

        Comment

        Working...
        X