I would like to write an excel sheet that lists the make of cars in sysuse auto by their trunk space. For example:
To do this, I have made a local with excel column names and have tried to loop through values of trunk:
The column local properly displays the next column A1, B1, C1, etc..., but the excel that is produced only has data in the A column with the names of the makes from the last trunk value.
Any advice on how should I be using the local column value in the cell option?
| 5 | 6 | 7 | 8 | 9 |
| Honda Civic | Datsun 200 | Chev. Monza | Datsun 210 | Merc. Bobcat |
| Pont. Sunbird | Datsun 510 | Toyota Corolla | ||
| Pont. Firebird | Datsun 810 | Ford Fiesta | ||
| Dodge Colt | Chev Chevette | |||
| Plym. Sapporo |
Code:
sysuse auto, clear
local excel_columns
* make a list of excel column names
foreach first in "empty" "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" {
foreach second in "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" {
if "`first'" == "empty" {
local excel_columns "`excel_columns'" "`second'1"
}
if "`first'" ~= "empty" {
local excel_columns "`excel_columns'" "`first'`second'1"
}
}
}
* this needs to start at 2 because the first 'word' of `excel_columns' is a space
local counter = 2
* make a local with the values of trunk
levelsof trunk, local(trunk_sizes)
foreach size in `trunk_sizes' {
* make local column with the excel column that corresponds to the iteration of the loop
local column : word `counter' of `excel_columns'
* check that the correct column is being stored
disp "`column'"
preserve
* label variable so that it can be column header
label variable make "Makes with trunk size: `size'"
* keep only entries that have the trunk size for the loop we are on
keep if trunk == `size'
* export the make value to the column stored in the local
quietly: export excel make using "..\Data\test.xlsx", sheet("Makes by trunk size") sheetmodify cell(``column'') firstrow(varlabels)
restore
local ++counter
}
Any advice on how should I be using the local column value in the cell option?

Comment