America’s Schools, Part 2: Eyeing the Pupil Data

19 Sep

The question with which we wound up the previous post bears repeating, so let me repeat it: does a cognizance of the data quality issues that compromise the US school dataset inflict a failing grade upon the the workbook? That is, are we right to proceed with a look at the data just the same and give them a proper hearing, or should we bail out and take our pivot tables elsewhere?

I’d allow that the answer I submitted in that post bears repeating too – i.e., something like a yes. It seems to me that an analysis should properly go ahead, because the weight of the records – all 97,000 or so of the usable ones (let’s remember that number) – should, in virtue of its very size, synergize a plausible summary of the shape and quantity of America’s schools. Again, of course, the numbers are “wrong”; but they’re invariably wrong for any demographic take built on US census data, which after all date from 2010. Still, some general picture of the country’s institutional landscape should be there for the limning, if we’re persuaded.

We can commence, then, by performing a simple count and break out of schools by state:

Rows: STATE

Values: STATE (Sorted, Largest to Smallest)          

I get, in excerpt:

school1

 You’re not likely to be surprised by the above. American’s most populous state, California, predictably registers the most schools, though a check of Wikipedia’s state population totals furnished both for 2010 census aggregates and 2016 estimates points to a relation between population and school numbers that isn’t quite linear. Note in addition that our pivot table makes no place for the 28 schools in American Samoa, and in this case it could have; you’ll recall that we provisionally banished that territory’s records from the data because of the unavailability of its student totals. But here because we’re counting school names alone, the AS data could have been accommodated – simply because its school names, at least, are indeed listed.

Next, we could just as easily consider the average number of students per school by state, but before pressing ahead entertain a pre-verification surmise: namely, do the more populous states average more students per school? That’s a sensible conjecture, but one that must by no means invariably follow; after all, it’s possible that the sparser states simply maintain fewer schools, whose average size compares with the denser ones.

Let’s see. You can leave STATE alone in Values, and add to it ENROLLMENT, ticking Average. Then sort the results by ENROLLMENT. I get, in part:

school2

That’s Guam at the head of the class, its 40 schools averaging 781 students per institution (again, the bundle of 55 “STATEs” owes its hyper-count to the inclusion of American territories). At bottom sits the scantly populated Montana, whose per-school average of 171 makes it easy for teachers to space their students at exam time, if nothing else.

The disparities here, then, affirm a most mixed set of students-per-school averages, recalling the question if the numbers of schools by state indeed correlate with average school size. A rough read on that relationship becomes available with CORREL, in my case looking like this:

=CORREL(B4:B58,C4:C58)

And that expression evaluates to .3117, mustering a loose but meaningful association between the two variables – that is, as the number of schools across the states ascend, so does average class size. At least slightly.

And what of teacher-student ratios across the states? Again, the incipient question, one we’ve submitted several times in the past, needs to be asked and answered: does one calculate the ratios by according equal weight to every school irrespective of absolute school size, or does one realize a grand average of all of a state’s students divided by all its teachers (apparently defined here as Full Time, and so perhaps  deeming two half-time instructors as one full-timer) instead?

In fact, both alternatives are credible. There may be good analytical reason to treat schools as equally-sized entities in the averages, in the same way, for example, that we would could compare the standards of living of residents in different countries. And weighting 100 and 1000-student schools equivalently can’t be worse than granting one vote to every country in the United Nations General Assembly or apportioning two US Senators to each state, can it?

But before we tangle with the numbers we need to broaden our look at the FT_TEACHER field, because a measurable batch of records there reports faculty complements at zero or in the negative numbers. Sort the field Largest to Smallest, and lower a blank row atop the first zero. But you know that routine.

Now if we play the above option, by in effect averaging each student-faculty ratio, we need to title the next available column (where that is depends on how many fields you deleted in last post) StuStaffRatio or something like it, and simply enter a formula in row 2 dividing ENROLLMENT by FT_TEACHER and copy down (again, column references may vary). Back in the pivot table, you need to rewrite the range coordinates of the source data set (in PivotTable Tools>Analyze>Change Data Source.), and follow up by recruiting StuStaffRation into Values, averaging the results to two decimal points. I get, in excerpt, after sorting the field Largest to Smallest:

school3

The inter-state variation is considerable, and it’s most noteworthy that, large school sizes notwithstanding, Guam has managed to insure a pleasingly low (13.75) student-to-teacher proportion – so low you can’t see it in the screen shot – with California faring worst, at 23.76.

Now a suitable null hypothesis might foretell a perfect correlation between average enrollments and faculty sizes, irrespective of the absolute state numbers involved. Thus alerted to that prospect, we could write

=CORREL(C4:C58,D4:D58)

I get .4076, pretty serviceable by social-scientific standards, but surely not a 1. In other words, some positive association obtains between school student sizes and their teaching teams.

And speaking of school numbers, if you sort the ENROLLMENT field Largest to Smallest you’ll discover the honors going to the Ohio Virtual Academy, an online institution that serves Kindergartners through 12th graders and 11640 students – somewhere (its governmental web page counts 11278 as of the 2014-15 school year).

That means there’s some crossing-guard monitors in Ohio with a whole lot of time on their hands.

Advertisements

America’s Schools, Part 1: Some Truants Among the Data

8 Sep

The segue is inadvertent, but calling up a census of America’s schools look right after our look at New York school attendance data with makes for a deft transitioning, if I may say so myself, and I think I’ve just granted permission to do so.

This nationwide listing -105,000 institutions strong – is curiously archived in a site putatively devoted to information about hurricane Harvey. I’m not sure about the placement, but that’s where it is.

And it’s pretty big, as you’d expect, counting 105,087 schools in its fold and pitching 24 MB at your hard drive, after a download and a save as an Excel workbook. (Note: the data unroll stats for the country’s public – that is, government operated – schools only. The very large number of private and sectarian institutions diffused across the US are thus excluded from the inventory.) And if you run a simple SUM at the base of column AC, the field storing student enrollment numbers, you’ll wind up with 50,038,887, and that’s pretty big, too.

But of course, that number can’t get it exactly right. For one thing, the overview introducing to the workbook tells us that the data feature “…all Public elementary and secondary education facilities in the United States as defined by…National Center for Education Statistics…for the 2012-2013 year”. And since then a few hundred thousand little Justins and Caitlins will have moved on to other venues, to be replaced by littler Treys and Emmas – and the turnover just can’t be equivalent. Moreover the (apparent) Source Dates recorded in X track back to 2009 in many cases, though I don’t completely know how those dates are to be squared with the 2012-2013 reporting period.

Now apart from the as-usual column autofits in which the dataset obliges you, you may also want to shear those fields likely not to figure in any analysis, though that of course is something of a judgement call. In view of the virtual equivalence of the X and Y data in A and B with those in the LATITUDE and LONGITUDE parameters in S and T, I’d do away with the former pair. I’d also mothball ADDRESS2 (and maybe ADDRESS, too – will you need their contents?) I’d surely dispense with the NAICS_CODE entries, as each and every cell among them declaims the same 611110. And I think VAL_METHOD, VAL_DATE, SOURCE (storing basic information about the school committed to web sites), and probably SHELTER_ID could be asked to leave as well, lightening my workbook by about 5.3 MB all told. On the other hand, WEBSITE appears to have done nothing but clone the contents of SOURCE and as such could assumedly be dispatched as well, but I’ve since learned that the sites offer up some useful corroborating information about the schools, and so I’d retain it. But a field I would assuredly not delete, in spite of my early determination to do so, is COUNTRY. I had misled myself into believing the field comprised nothing but the USA legend, but in fact it entertains a smattering of other geopolitical references, e.g. GU for Guam, PR for Puerto Rico, and ASM for what I take to be American Samoa, for example.

I’m also not sure all the Manhattan schools (the ones in New York county, that is) display their correct zip codes for what it’s worth, and it might be worth something. The Beacon High School on West 61st Street is zip-coded 10022, even as it belongs, or belonged, to 10023 (though that wrong zip code informs a review of the school by US News and World Report); but the error may be excused by an updated reality: the Beacon School moved to West 44th Street in 2015, calling the timeliness of our data into a reiterated question. I’m equally uncertain why the Growing Up Green Charter School in Long Island City, Queens is mapped into New York county.

More pause-giving, perhaps, are the 1773 schools discovered inside New York City’s five counties – New York, Queens, the Bronx, Brooklyn (Kings County), and Richmond (or Staten Island; note that a Richmond county appears in several states in addition to New York). You’ll recall that our posts on New York’s attendance data, drawn from the city’s open data site, numbered about 1590 institutions. Thus any story-monger would need to be research the discrepancy, but in any case it is clear that the dataset before us errs on the side of inclusiveness.

But a lengthier pause punctuates a Largest-to-Smallest sort of the ENROLLENT field. Drop down to the lowest reaches of the sort and you’ll find 1186 schools registering a population of 0, another 1462 reporting -1, 4493 sighting -2 persons on their premises, and 91 more submitting a contingent of -9. Moreover, you’ll have to think about the 5399 schools counting a POPULATION (a composite of the ENROLMENT and FT_TEACHER fields) of -999. It’s not too adventurous to suggest that these have been appointed stand-ins for NA.

In addition, we need to think about the schools declaring only 1 or 2 students on their rolls. Consider for example the Marion Technical Institute in Ocala Florida and its 1 student and 34 full-time teachers. Visit its web site, however, and we encounter a more current student enrollment of 3 and a FTE (full-time equivalent) instructional complement of 37 (as of the 2015-16 school year), not very far from what our database maintains. But at the same time many of the 1-student schools are accompanied by FT_TEACHER values of 1 or 0 as well, and these microscopic demographics demand scrutiny. The web site for Bald Rock Community Day school in Berry Creek, California, for example, reveals no enrolment/teacher information, for example.

What to do, then? It seems to me that any school disclosing a negative or zero enrollment – and now sorting the ENROLLMENT field highest-to-lowest will jam all of these to the bottom of the data set – be disowned from the data set via our standard interpolation of a blank row atop 97407, where the first zero figure sits. We’ve thus preserved these curious entries for subsequent use should their other fields prove material.

And all that begs the larger question tramping, or trampling, through the data: How much time, effort, and money should be properly outlaid in order to support the vetting of 100,000 records? Multiple answers could be proposed, but there’s a follow-on question, too: In light of the issues encountered above, hould the data in the public schools workbook should be analysed at all?

Well, if we’ve come this far, why not?

NYC School Attendance Data, Part 2: What I’ve Learned

23 Aug

Once we’ve decided we’re pleased with the New York City school attendance data in their current, emended state (per last week’s post), we can move on to ask some obvious but edifying questions about what we’ve found.

First, a breakout of attendance percentages by day of the week is something we – and certainly Board of Education officials – will want to see. In that connection, we again need to decide if we want to break out the attendance percentages arrayed in the %_OF_ATTD_TAKEN field, and/or the numbers we derived with our ActualTotals calculated field, the latter according numerical parity to each and every student; and as such, it seems to me that ActualTotals is fitter for purpose here (of course we could deploy both fields, but let me err on the side of presentational tidiness here).

But in the course of tooling through and sorting the data by the above %_OF_ATTD_TAKEN, I met up with a few additional complications. Sort that field Smallest to Largest, and you’ll have gathered a large number of records reporting days on which absolutely no students attended their respective schools – 7,245 to be exact; and while an accounting for these nullities can’t be developed directly from the dataset, we could be facing an instance of mass, errant data entry, and/or evidence of a requirement to furnish a daily record for a day on which classes weren’t held. And in fact, over 14,000 records attest to attendance levels beneath 50% on their days, and I don’t know what that means either. It all justifies a concerted look.

But in the interests of drawing a line somewhere, let’s sort %_OF_ATTD_TAKEN Largest to Smallest and split the data above row 513796 – the first to bear a 0 attendance percentage – with a blank row, thus preserving an operative, remaining dataset of 513974 records. But still, I’d submit that more thinking needs to be done about the low-attendance data.

Returning now to our day-of-the-week concerns, the pivot table that follows is rather straightforward:

Rows: Day

Values: ActualTotals

I get:

attend1

(Note that you’d likely want to rename that default Sum of ActualTotals header, because the calculated field formula itself comprises an average, in effect – NumberStudents/REGISTER*100. You’ll also want to know that calculated fields gray out the Summarize Values option, and thus invariably and only sum their data. Remember also that 2 signifies Monday.)

I for one was surprised by the near-constancy of the above figures. I would have assumed that the centripetal pull of the fringes of the week – Monday and Friday – would have induced a cohort of no-shows larger than the ones we see, though attendance indeed slinks back a bit on those two days. But near-constancy does feature strikingly in the middle of the week.

And what of comparative attendance rates by borough? Remember we manufactured a Borough field last week, and so:

Rows: Borough

Values: ActualTotals

I get:

attend2

By way of reorientation, those initials point to these boroughs:

K – Brooklyn

M – Manhattan

Q – Queens

R – Richmond (Staten Island)

X – The Bronx

The disparities here are instructive. Queens students are the literally most attentive, with Bronx students the least. Of course, these outcomes call for a close drilldown into the contributory values – e.g., economic class, ethnicity, and more – that can’t be performed here.

We can next try to learn something about attendance rates by month, understanding that the data encompass two school years. Try

Rows: Date (grouped by Months only)

Values: ActualTotals

I get:

attend3

The school year of course commences in September, with those early days perhaps instilling a nascent, if impermanent, ardor for heading to class. We see that attendance peaks in October, and begins to incline toward the overall average in December.

The question needs to be asked about June, or Junes, in which the attendance aggregate crashes to 85.21%, deteriorating 4.69% from the preceding May(s). While explanations do not volunteer themselves from the data, an obvious surmise rises to the surface – namely, that students beholding the year’s finish line, and perhaps having completed all material schoolwork and exams, may have decided to grab a few discretionary absences here and there. It’s been known to happen.

But let’s get back to those zero-attendance days and their polar opposite, days in which every student on a school’s roster appeared, or at least was there at 4 pm. The data show 1641 records in which each and every enrollee in the referenced institution was there, a count that includes 31 days’ worth of school code 02M475, i.e. Manhattan’s renowned Stuyvesant High School; a pretty extraordinary feat, in view of the school’s complement of around 3,300. And while we’re distributing kudos, mark down September 21, 2016, the day on which all 3,965 of Staten Island’s Tottenville High School registrants showed up, and June 24 of that year – a Friday, no less – on which the entire, 3,806-strong enrollment of Queens’ Forest Hills High School settled into their home rooms. But ok; you could insist that these laudable numbers should likewise be subjected to a round or two of scrutiny, and you’d probably be right.

Now for a bit of granularity, we could simply calculate the average daily attendance rates for each school and sort the results, and at the same time get some sense whether attendance correlates with school size as well. It could look something like this:

Rows: SCHOOL_DBN

Values: REGISTER (Average, to two decimals)

%_OF_ATTD_TAKEN (Average, to two decimals)

Remember first of all that a given school’s enrollment is by no means constant, swinging lightly both within and across school years. Remember as well that because you can’t average calculated field totals, I’ve reverted to the %_OF_ATTD_TAKEN field that’s native to the data set.

Sort by %_OF_ATTD_TAKEN from Largest to Smallest and I get, in excerpt:

attend4

That’s the Christa McAuliffe School (named after the astronaut who died in the Challenger explosion) in Bensonhurst, Brooklyn on the valedictorian’s podium, followed very closely by the Vincent D. Grippo school, (physically close to the McAuliffe school, too). And if you’re wondering, I find Stuyvesant High School in the 907th position, with its daily attendance average put at 90.87. Tottenville High, interestingly enough, pulls in at 1155 out of the 1590 schools, its average figuring to a below-average 87.43. At the low end, the Research and Service High School in Brooklyn’s Crown Heights reports a disturbing 41.84% reading, topped slightly by the Bronx’s Crotona Academy High School (remember that you can learn more about each school by entering its code in Google). These readings merit a more determined look, too.

And for that correlation between school size and attendance: because my pivot data set out on row 4, I could enter, somewhere:

=CORREL(B4:B1593,C4:1593)

I get .170, a small positive association between the parameters. That is, with increased school size comes a trifling increment in attendance rates.

But if you want to learn more about correlations you’ll have to come to class.

NYC Attendance Data, Part 1: Some Necessary Homework

14 Aug

This open data thing is cool; they’ve even drummed up a report, available to every inhabitant on planet earth give or take a few censors, on my very own elementary school, P.S. 165 in Queens, New York City.

No; you won’t find my name large-typed anywhere in the record of 165’s distinguished alumni, but this is an academic status report, after all, and I’m prepared to forgive the omission. The larger point – I think – is that data – attendance data – about P.S. 165, and all of its 1600 or so companion institutions comprising the New York’s public school system, are present and accounted for here. Click the Download link, proceed to the CSV for Excel option (there’s a Europe regional-formatted version there, too), and wait for its 524,000 records to find their place in your virtual lecture hall.

The worksheet roll-calls attendance numbers for the days filling the September-June school years 2015-16 and 2016-17, and don’t be fooled by its understated five fields; at least three additional parameters can be easily synthesized from those five, and to productive effect. (Note: Apart from the need to autofit the field columns, keep in mind that the entries in the REGISTER field tabulate the school’s official enrollment as of the given day, and not the number of students who actually made their way to class.)

But the data do require a touch of vetting before the analysis precedes. Row 455543, if you’re keeping score, is in effect something of a blank, save a cryptic notation in the A column that won’t further our reporting interests. As such, the row should be, er…expelled. But another, more troublesome set of entries needs to be confronted and ultimately unseated from the dataset.

Start by running this pivot table at the records:

Row: DATE (ungroup if you’re on Excel 2016)

Values: REGISTER (sum)

Sort Largest to Smallest. I get, in excerpt:

att1

The two uppermost dates – January 13, 2016 and February 2 of that year – exhibit suspiciously large register totals, just about doubling the other sums. It appears as if the records for that pair of dates have simply, if unaccountably, been duplicated – and as such one-half of these have to be sent on their way.

And that sounds to me like a call for Remove Duplicates. Click its trusty button on the Data ribbon, and tick:

att2

Follow through, and you’ll be told that 3172 duplicate values – which sounds precisely duplicative – have been found and shed from the dataset.

Then inspect the lower reaches of that original sort and you’ll come upon more than 20 days, the great bulk of which are dated somewhere in June (i.e. the last month of a school year), with aggregate totals less than 800,000 – substantially beneath the totals above them. I suspect some reporting shortfall is at work, and indeed the legend attaching to the data on the Open Data site states the numbers may not be final “…as schools continue to submit data after preliminary report is generated”. We’re also left to explain April 18 of this year, for example, a date on which we’re told 819 students actually appeared, on what was the last day of the spring recess. Presumably they were there for some good educational or administrative reason – or the record is there by mistake (those 819 come from two schools, the Bard High School Early College institution in Queens and the School of Integrated Learning in Brooklyn).

Now we can go about deriving those three fields I advertised above. I’d first head into column F, title it Day, and enter in F2:

=WEEKDAY(B2)

And copy down. We’ve certainly seen this before; WEEKDAY will tease out the day of the week from a date-bearing cell (with 1 denoting Sunday by default), and so presages any look at attendance figures by day.

Next, we could entertain an interest in breaking out attendance data by each of New York’s five boroughs – these the object of a neat, single-lettered code in the SCHOOL_DBN field, squirreled in the third position of each code:

K – Brooklyn (Brooklyn is officially named Kings County)

M – Manhattan

Q – Queens

R- Richmond (aka Staten Island)

X – Bronx

Thus we could name G1 Borough and enter in G2:

=MID(C2,3,1)

That is, the above expression collects one character from C2, starting (and finishing) at the third character in the cell – in the case of C2, X, or Bronx. (By the way, if you enter a school’s code in Google you’ll be brought to its web page, including P.S. 165 and 25Q425, or John Bowne High School, another of my academic ports of call). Then copy down G.

The final of our three supplementary fields would simply return the actual number of students who appeared in a given school on a given day, or at least the ones who were there to be counted at 4 pm; and while of course the dataset already reports schools’ daily attendance percentages, information that might tell us what we want to know, we’re again made to revisit an old but material problem: by  manipulating percentages alone we in effect weight each school identically, irrespective of student body size. And in fact that treatment might come to serve certain analytical purposes rather well, because there may be good reason to regard schools as equivalently important units. But for the same money we may want to have it both ways, by compiling stats that give each school its proportionate due. Thus we can title H NumberStudents and enter, in H2:

=ROUND(E2*D2/100,0)

If that expression seems needlessly ornate, keep in mind that the values holding down the %_OF_ATTD_TAKEN field in D aren’t percentages, but rather percentages multiplied by 100; as such they need to be cut down to size by a like decrement. And the ROUND addendum means to quash any decimals that don’t quite do the results justice. After all, if 84.2% of a school’s 1,042 charges show up, should we let the Board of Education know that 905.15 of them have been sighted in the building? I’d bet that .15 has at least foot out the door.

But do these definitional niceties matter anyway? We can find out by first setting a pivot table in motion and churning out a calculated field, which I’ll call ActualTotals:

att3

(And no, you won’t need parentheses around the two fields.) As for the 100 multiplier, it will put the results in alignment with those %_OF_ATTD_TAKEN numbers, which again exhibit a similar order of magnitude – that is, the latter comprise percentage data times 100.

The pivot table looks then like this:

Rows: SCHOOL_YEAR

Values: %_OF_ATTD_TAKEN (average, to two decimals)

ActualTotals (average, two decimals)

I get:

att2

The differences are small but real.

But ok, class; let’s take recess. Just remember to be back by…4 pm.

 

Hit or Miss : Baseball’s Home Run and Strikeout Profusions

31 Jul

See the ball, hit the ball, advised the aphorist Pete Rose, with his winsome epigrammatic flair. And in fact, in the course of his day job as a major league baseball player, Mr. Rose took his reductive prescription to heart: the record shows he hit the ball 12,910 times, 4,256 of which resulted in that outcome curiously, and redundantly, called a… hit.

To be sure, Rose missed the ball – or struck out – 1,143 times, but as a percentage of his 14,053 times at bat, his 8.13% worth of misses is impressively low. And Rose would be interested to know that major league batters are missing the ball more often than at any time in the history of his chosen profession.

Batters in 2016 struck out 23.5% of all their at-bats, or .235 per the game’s three-digit formatting heritage (so don’t ask me why earned-run averages are squeezed to merely two decimals, though I have a theory); and the strike-out proportion thus far for this year (courtesy of Baseball-Reference.com) has ticked up to .241.

But that narrative of futility has been thickened by a sub-plot: major-league batters are also hitting more home runs than ever, and the dialectic of hit-or-miss isn’t quite the contradiction it seems. After all, you’ll agree it’s easy to miss a 98-mile-per-hour fastball – all the more so if your neurons are forced to contend with a 78-mile-per-hour curve ball instead. Surprise. But manage to make contact with that fastball and the results could go a long way (see this consideration of the home-run/strikeout relationship in the New York Times, with particular attention paid to the home-run half of the equation).

To learn a bit more about the home-run/strike out antimony it would be a good idea to consult Sean Lahman’s free, go-to Baseball Database, as we have in earlier posts (look here, for example. Remember that Mr. Lahman will happily attend contributions.) Click the 2016 – comma-delimited version link, and another click upon the resulting zip file will empty its spreadsheet files into its folder. Then call up the Teams workbook. (Note Lahman advises that the files work best in a relational setting, but our analytic interests here can be sufficiently served by Teams all by itself.) Once we’ve gotten here we can throw a few simple calculated fields into a pivot table to productive effect, and join them up with a couple of applications of the CORREL function for our information.

To start, we could drum up yearly strikeout percentages – that is, strikeouts divided by at bats, and then for presentation purposes proceed to group the outcomes by say, bins of five years:

Rows: yearID

I’d group the years thusly:

hr1

I’ve earmarked the above span because some of the pre-1910 years have no strikeout data, and because the 1912-2016 interval comprises 105 years, yielding 21 equally-sized tranches.

Next I could devise this calculated field, which I’ve called sopct:

 

hr2

And garb the resulting values with this custom format:

hr3

And filter out the <1912 data.

When the dust settles I get:

hr4

The ascendancy of strikeouts is clear. Note the distinctly impermanent fallback in the strikeout percentages in the 1972-1981 era, a predictable and intended consequence of the lowering of the pitching mound in 1969 and its literal levelling of the playing field for hitters. But nevertheless the trend soon recovered its arc.

We could next calculate a similar field for home runs, calling it hrpct:

hr5

Applying a similar grouping and formatting to the field, I get:

hr6

The trendline is considerably flatter here, and indeed seems to have peaked during the 1997-2001 tranche – not surprisingly, because it was during that fin de siècle epoch that steroid use among ballplayers apparently peaked as well, thus fomenting, among other mighty anomalies, Barry Bonds’ surreal 73 home runs in 2001, and in 476 at bats.  Ungroup the yearID field momentarily and treat the numbers to a four-decimal format, and you’ll discover a home-run high of .0340 in 2000 – but note the .0339 for last year as well, succeeded in turn by this year’s all-time, relatively drug-free .0368 (again, check Baseball Reference for the to-the-minute totals).

Now what then about the association between strikeouts and home runs? Baseball common sense would predict an appreciably positive correlation between the two; the harder the swings at those fastballs, one could suppose, the more misses – but along with these flows the expectation of more long balls, too, once and if bat actually meets ball.

To palliate our curiosity, we can trot out both sopct and hrpct into Values, and continue to leave yearID ungrouped. With the strikeout and home run values stationing themselves into columns B and C and the year 1910 making itself home on row 43 – a positioning that by extension locks the 2016 data into row 149 – I can enter, somewhere:

=CORREL(B43:B149,C43:B149)

That expression returns a most, almost unnervingly impressive, .845, shouting the view that, as strikeouts go, so do home runs – and virtually in lockstep.

We can then go on ask about the relationship between strikeouts and batting average. Might it follow that, with the increasing, overall failure to hit the ball, averages should falter correspondingly – simply because fewer balls will have been put into play? You can’t get a hit if you don’t hit the ball, it seems to me. Or do we allow that because hard swingers hit the ball harder (when they do) – that a hard-hit ball is harder to catch?

We can check that one out. We can mint still another calculated field, which I’ll call baagg (for batting average aggregate):

hr7

Replace hrpct in Values with baagg, leave sopct in place, and because the operative ranges don’t change the CORREL we authored above should rewrite itself, yielding -.477 – a notable inverse association (that’s a minus sign preceding the value, not a dash). That is, as strikeouts mount, batting averages do tend to respond downwards. And while it’s true that -.477 isn’t .845, most social scientists would be thrilled to even have that number crunched upon their desk.

And I suspect Pete Rose is smiling, smugly, too.

The Supreme Court Database, Part 2: Doing Justice to the Numbers

17 Jul

With 70 years and 61 fields worth of skinny on the 78233 Supreme Court rulings spread across 1946 through 2015, there should be a lot to learn from all those data – once we decide what questions could profitably be asked of them.

What about seasonality? That is, do Court decisions, and for whatever reason, issue from the hands of opinion writers in equal measure across session months?

They don’t. Try this pivot table:

Rows: dateDecision (grouped by Months only)

Values: dateDecision (count)

dateDecision (again, by % of Column Total)

I get:

scourt1

Note that yearly court sessions commence on the first Monday in October, and typically proceed through late June or early July (for more, look here. The October inception point means in turn that the term years recorded in column K actually subtend only the later months of that year, and so extend well into the succeeding one. For example, the earliest decision disseminated in 1946 was time-stamped November 18 of that year.)

We see that more than half of all Court decisions were ratified in the April-June quarter, notably swelled by the aggregate June efflorescence. One could conjecture that a need to dispose of a case backlog pressed hard against impending summer recesses might explain the flurries in June.

And what about what the database calls its issue areas, i.e. the categorical domains of the cases pled before this court of last resort, and their yearly distributions thereof? The issue area field in column AO assigns the litigations to 14 broad classificatory swaths defined here; these can be copied and pasted to an empty range in the workbook and regarded as a lookup table (which we’ll name caseIssue).

Next, enter the field title caseIssue in BK1, the free column alongside our improvised uniquecount field (see last week’s post), and type in BK2:

=VLOOKUP(AO2,caseissue,2)

And copy down (you may also want to drop a copy > paste special atop the results, a modest austerity measure that stamps hard-coded equivalents of the outcomes that condensed my file by about 600K.

But now we are made to return to the question imposed upon us in the previous post: because our data set remembers the votes of individual Justices for each case, the case ids naturally appear recurrently and, for our purposes here, redundantly – up to nine times each.  In the last post we applied a formula to isolate single instances of each case in order to realize our count of cases heard by year. Here we need to conduct another count of sorts of unique entries, but one that at the same time preserves the categorical identities of the cases.

So I banged together this pivot table, for starters:

Rows: Term

Caseid

Caseissue

In addition, click Design > Report Layout > Repeat All Item Labels, a decision that reiterates the term (year) data for each record, thus overriding the standard pivot table default posting of each year but once. Turn off Grand Totals, too, and make sure to select the Tabular Form report layout.

Doing what pivot tables are trained to do, each caseid is singled out, per this screen shot excerpt:

scourt2

Then filter out the #VALUE item from caseissue; these represent records (485 of them) for which no issuearea data avails. Note that the Values area remains unpopulated, because we’re not concerned here with any aggregated data breakout – at least not here. Rather, we want to treat the table as a de facto data set, itself to be subject to a second pivot table.

And is that prospect thinkable? It is, and a scrounge around the internet turns up a few slightly variant means toward that end. One strategy would first have the user select the entire table and superimpose a Copy > Paste Values overwrite upon it, downgrading the table, as it were, into a mere standard set that lends itself to a perfectly standard pivot tabling.

But that rewrite isn’t necessary; in fact, you can pivot table the pivot table straight away, by first clicking outside the pivot table and, by way of one alternative, now clicking Insert > Pivot Table. At the familiar ensuing prompt:

scourt3

Select the entire pivot table (but I was unable to enter the default table’s name, e.g. PivotTable1, in the field, however). Note in addition that while conventional pivot tables default their location to New Worksheet, Existing Worksheet has been radio-buttoned here; but I’ll revert to type and opt for New Worksheet, because I want the table to begin to unfold as far to the left of the worksheet as possible – that is, column A. Click OK, and the fledgling second pivot table and Field List check in onscreen.

Then the standard operating procedure resumes:

Rows: Term (grouped in tranches of 5 years)

Columns: caseissue

Values: caseissue (Count, necessarily, by % of Row Totals; as we’re now working with percentages, turn off the Grand Totals that will invariably figure to 100%.)

I get:

scourt4

I hope the shot is legible. If not, the table is yours for the clicking.

I’m not sure the outcomes elaborate “trends”, but that hardly discommends them from analysis. You’ll note a rather decided drop in Federal Taxation and Union-related cases, for example, and a general upswing in Criminal Procedure hearings, even as other categories (Due Process and even Civil Rights) fail to slope straightforwardly; in any event the percentages need to be read against the absolute numbers contributory toward them, because they aren’t always large. With what is in effect a matrix comprising 14 year groupings by as many case categories, those 196 potential intersections map themselves to 8683 cases; do the math, and some of those quotients are likely to be small.

And there’s a postscript to all this, of course. Last week’s post resorted to a moderately fancy formula that managed to seek out but one instance of each Court decision, preparatory to our count of caseloads by year. Now I realize that we – I – could have done the pivot-table-of-pivot-table thing to bring about the same result, and with only one field. That is, for the first pivot table-cum-data set:

Rows: Term (in conjunction with Repeat All Item Labels)

Case ID (and Tabular Form report layout)

Then pivot table the above:

Rows: Term

Values: Count

Voila.

 

Hey, it’s my blog – I’m allowed to learn something, too.

The Supreme Court Database, Part 1: Doing Justice to the Numbers

4 Jul

It stands to reason as a matter of near-definitional necessity that open data in a democracy would crank open a window on its judicial system; and the United States Supreme Court seems to have obliged. The Supreme Court database, a project of Washington University that has adapted the foundational labors of the late Michigan State University Professor Harold J. Spaeth to the spreadsheet medium, affords researchers an educative profusion of information about Court doings – once you understand what you’re looking it.

That qualification broadcasts a caution to unlettered laymen such as your faithful correspondent, who’s still can’t understand why chewing food with one’s mouth open hasn’t been declared unconstitutional.

But enough about me. In fact, the database comprises a collection of datasets that breaks the Court information along a pair of variables, Case and Justice Centered Data, each of which supplies four variably-formatted sets tied to the above parameters. Here I’ve downloaded Cases Organized by Supreme Court Citation:

court1

The workbook details yearly vote activity of Court justices dating from 1946 through 2015 (and you’ll note the parallel compendium for votes cast between 1791 and 1945); but again, you’ll need to appreciate what the workbook’s 61 fields want to tell you. (You can also conduct detailed data searches on site’s elaborate analysis page.)

For guidance, then, turn to the site’s very useful Documentation page, wherein the meanings behind the headers/fields are defined via the links holding down the page’s right pane (one quirk: the pane arrays the header/variables by category, and not by the sequence in which they actually appear in the workbook).

But we needn’t think too deeply about the field’s yields in order to issue a telling first read on the Court’s caseloads. We can move to break out the number of cases the Court has considered by year, by counting the number of unique case ids posted to column A. But there’s a hitch, resembling the one that has stalled us in a number of previous posts: because the records identify each justice’s vote per case, the case ids naturally appear in quantity – in the great majority of cases nine times, registering the number of sitting justices at any given time. (The number isn’t invariably nine, however, because occasional vacancies depress the total.)

But whatever the justice count, we want to reckon the number of unique cases the Court heard during a given year. We’ve entertained a number of takes on the matter in the past, and here’s another one, this a reasonably elegant formulation adapted from a solution advanced here. Slide over to column BJ, the one adjoining the dataset’s last occupied field, name it UniqueCount, and enter in BJ2:

=IF(COUNTIF(A$2:A2,A2)=1,1,0)

Copy the above down B (note that, owing to processing issues, the copy down may take some time).

What is this expression doing? It’s conducting a COUNTIF for the appearance of each entry in the A column (positioned in the formula as the COUNTIF criterion), the frozen A$2 serving to progressively expand the criterion range as the copy-down proceeds. If any instance of the formula returns an aggregate count exceeding one, the IF statement instructs it post a zero. Thus we’re left in uniquecount with a collection of 1’s and 0’s, the 1’s if effect counting each case id once and ignoring any additional appearances of that id. (Note as well that here we need to conduct a row-by-row count of unique entries, because the 1’s need to be summed inside the pivot table. Other formulas will deliver the total

number of unique elements in a solitary formula; look here, for example for a pretty well-known array-formulaic solution.)

Once we’ve harnessed the UniqueCount values, i.e. we’ve winnowed the data for but one citation of each case, we can put these immediately to work in this pivot table:

Rows: Term

Values: uniquecount

I get (in excerpt, after having frozen the title row):

court2

Beginning with the early 90s, the Court appears to have, for whatever reason, imposed a dramatic scale-down in cases heard see this analysis of the phenomenon). The Court adjudged 197 cases in 1967; by 2014 the number had contracted to 70.

For another, most interesting gauge of the court’s collective disposition, we could turn to the Direction parameter in column BF. Its entries are tidily binary; a 1 attests a justice’s conservative orientation to the vote, a 2 a liberal tilt. (Of course those conclusions require something of a judgement call; for a detailed accounting of the Database’s coding determinations look here.)

Some basic math should help ground the analysis. If the Court rules conservatively through a 5-to-4 vote, its Direction aggregate will figure to 13 – 5 1’s and 4 2’s, or a Direction average of 1.44 – 13 divided by 9. An equivalent liberal majority comes to 14, or a 1.56 average. A theoretical ideological midpoint of 1.5, then, centers the averages.

With those understandings in tow we can develop what could be called a directional index of Court votes, e.g.

Rows: Term

Values: Direction (average, rounded to two decimals).

I get, again in excerpt:

court3

Of course, you’ll want to peruse all the averages, but the data seem to affirm the Court’s measurable movement to the right. From a relative liberal high of 1.70 in 1963, the averages begin to descend, first falling though the 1.5 divide in 1975, bottoming out in 1998 and 2002 at 1.40. The 2015 average of 1.49, however, plunks down right in the middle of the road – and a grouping of the terms in five-year tranches situates the votes for latest available interval right atop the center stripe (or 1.501996, if you insist).

court4

A logical follow-on, then, would have us average the voting propensities of individual justices, names nicely paired with their votes in the justiceName field in BC. For good measure we can easily tally the number of decisions each Justice opined, by simply counting the number of times his or her name appears in the field (of course a Justice votes only once per decision):

Rows: justiceName

Values: Direction (average, to two decimals)

justiceName (count)

After sorting the averages smallest to largest and pasting together two screen shot excerpts I get:

court5

Now those tabulations are instructive, albeit not wholly unpredictable. Justices Lewis Powell, Clarence Thomas, Warren Burger, and the late Antonin Scalia hold down the farthest-right positions, with William O. Douglas – a justice publicly renowned for his juridical liberality – pushing hardest towards the left, as it were. Chief Justice Earl Warren – famously lauded and/or scored for comparable takes on the law – isn’t far behind. And for the record it was William Brennan, among the post-1945 justices at least, whose 5325 votes marks him as the most participative; but at the same time remember that the 1946 divide artificially stunts the vote totals of justices whose appointments predated that year.

But time to recess for lunch. And I know – you’ll be watching closely to see how I chew my food.