Announcement

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

  • conformability error r(503) when looping matrix

    Hello statalists,

    I'm trying to loop some basic descriptive stats of age according to sex. Right now the matrix looks like this:

    age[1,5]
    mu_men sd_men mu_women sd_women p
    Age 48.584151 22.583488 51.528371 22.524248 .

    with codes:
    matrix age = J(1,5,.)
    matrix rownames age = "age"
    matrix colnames age = "mu_men" "sd_men" "mu_women" "sd_women" "p"

    tab1 sex if index==1

    local j=1
    local s=1 // s is for values of sex (1 = Men, 0 = Women)

    while (`s'>=0){

    quietly sum age if sex==`s' & index==1, detail
    local mu=r(mean)
    local sd=r(sd)


    matrix age[1,`j']=`mu'
    matrix age[1,`j'+1]=`sd'

    local s=`s'-1
    local j=`j'+2
    }
    But I would like to have the matrix to look like this:
    mu sd
    men
    women
    So I wrote the following codes:

    matrix age = J(2,3,.)
    matrix rownames age= "men" "women"
    matrix colnames age= "mu" "sd" "p"
    local s=1

    while (`s'>=0) {

    sum age if sex==`s' & index==1, detail
    local mu=r(mean)
    local sd=r(sd)

    matrix age[`s',1]=`mu'
    matrix age[`s',2]=`sd'

    local s=`s'-1
    }

    I end up getting this error message: conformability error
    r(503);

    When I list the matrix, this is what I get:
    mu sd p
    men 48.584151 22.583488 .
    women . . .
    Why am I getting this error? It seems to happen as soon as Stata is trying to run the second row. How do I fix it? I am using Stata 15.1 on a PC, thanks!
    Last edited by Kay Marcus; 18 Jun 2020, 05:23. Reason: edited tables

  • #2
    Welcome to Statalist.

    You have accidentally posted your topic in Statalist's Mata Forum, which is used for discussions of Stata's Mata language, which is different than Stata's command language, and different than Stata's matrix commands. Your question would have seen a more appropriate, and much larger audience if you had posted it in Statalist's General Forum.

    Also, if you have not already done so, take a look at the Statalist FAQ linked to at the top of this page for posting guidelines and suggestions.

    With all that said, your problem is that your code attempts to store the results for women (s=0) into row 0 of your matrix. That can't be right and may be what is causing the error. Perhaps the following untested changes will start you in a useful direction.

    Code:
    local s=1
    local j=1
    
    while (`s'>=0) {
    
    sum age if sex==`s' & index==1, detail
    local mu=r(mean)
    local sd=r(sd)
    
    matrix age[`j',1]=`mu'
    matrix age[`j',2]=`sd'
    
    local s=`s'-1
    local j=`j'+1
    }

    Comment


    • #3
      I see, sorry for the mispost. Thanks a lot for the response!

      Comment

      Working...
      X