Announcement

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

  • Building table with multiple variables using putexcel

    I want to create a simple table, where each row is a one of five response options (strongly agree, agree, neither agree nor disagree, disagree, strongly disagree), each column is a different variable, and the cell values are percent of column total. I can get Stata to loop through a varlist with each variable going on a new sheet, but I'd prefer the results all side by side in one sheet. My working code (where each variable gets its own sheet)

    Code:
    foreach x of varlist var1-var6 {
            local RowVar = "`x'"
                        tabulate `RowVar' , missing matcell(cellcounts)
                        mata: st_matrix("total", colsum(st_matrix("cellcounts")))
                                                 
    putexcel set file.xlsx, sheet(`x') modify open
         putexcel A2="strongly agree" A3="agree" A4="neither agree nor disagree" A5="disagree" A6="strongy disagree"
        putexcel B1="`x'"
        local B2=string(cellcounts[1,1]/total[1,1],"%9.3f")
        putexcel B2=`B2'
        local B3=string(cellcounts[2,1]/total[1,1],"%9.3f")
        putexcel B3=`B3'
        local B4=string(cellcounts[3,1]/total[1,1],"%9.3f")
        putexcel B4=`B4'
    local B5=string(cellcounts[4,1]/total[1,1],"%9.3f")
        putexcel B5=`B5'
    local B6=string(cellcounts[5,1]/total[1,1],"%9.3f")
        putexcel B6=`B6'
        putexcel close
    }
    I think it calls for tokenise to link the columns and the variables, but I can't figure out how to implement that.

  • #2
    Based on other posts here, I tried
    Code:
     foreach x of varlist var1-var6 {        
    local RowVar = "`x'"                    
    tabulate `RowVar' , missing matcell(cellcounts)                    
    mata: st_matrix("total", colsum(st_matrix("cellcounts")))    
    local colnum 2                                        
    putexcel set file.xlsx, sheet(type) modify open      
    putexcel A2="strongly agree" A3="agree" A4="neither agree nor disagree" A5="disagree" A6="strongy disagree"    
    local col =char(64 + `colnum' + 1)
    putexcel `col'1="`x'"    
    local B2=string(cellcounts[1,1]/total[1,1],"%9.3f")    
    putexcel `col'2=`B2'    
    local B3=string(cellcounts[2,1]/total[1,1],"%9.3f")    
    putexcel `col'3=`B3'    
    local B4=string(cellcounts[3,1]/total[1,1],"%9.3f")    
    putexcel `col'4=`B4'
    local B5=string(cellcounts[4,1]/total[1,1],"%9.3f")    
    putexcel `col'5=`B5'
    local B6=string(cellcounts[5,1]/total[1,1],"%9.3f")    
    putexcel `col'6=`B6'    
    putexcel close
    local ++colnum
    }
    This gives me two identical columns of data for var6.
    Last edited by Josephine George; 18 Nov 2021, 06:27.

    Comment

    Working...
    X