Tuesday, January 5, 2010

Why use R Statistical Software

From: http://datamining.togaware.com/survivor/Pros_Cons.html


*R is the most comprehensive statistical analysis package available. It incorporates all of the standard statistical tests, models, analyses, as well as providing a comprehensive language for managing and manipulating data.

* R is a programming language and environment developed for statistical analysis by practising statisticians and researchers.

* R is developed by a core team of some 10 developers, including some of the worlds leading Statisticians.

* The validity of the R software is ensured through openly validated and comprehensive governance as documented for the American Food and Drug Authority in XXXX. Because R is open source, unlike commercial software, R has been reviewed by many internationally renowned statisticians and computational scientists.

* R has over 1400 packages available specialising in topics like from Econometrics, Data Mining, Spatial Analysis, Bio-Informatics.

* R is free and open source software allowing anyone to use and, importantly, to modify it. R is licensed under the GNU General Public License, with Copyright held by The R Foundation for Statistical Computing.

* Anyone can freely download and install the R software and even freely modify the software, or look at the code behind the software to learn how things are done.

* Anyone is welcome to provide bug fixes, code enhancements, and new packages, and the wealth of quality packages available for R is a testament to this approach to software development and sharing.

* R well integrates packages in different languages, including Java (hence the Rpackage[]RWeka package), Fortran (hence Rpackage[]randomForest), C (hence Rpackage[]arules), C++, and Python.

* The R command line is much more powerful than a graphical user interface.

* R is cross platform. R runs on many operating systems and different hardware. It is popularly used on GNU/Linux, Macintosh, and MW/Windows, running on both 32bit and 64bit processors.

* R has active user groups where questions can be asked and are often quickly responded to, and often responded to by the very people who have developed the environment--this support is second to none. Have you ever tried getting support from people who really know SAS or are core developers of SAS?

* New books for R (the Springer Use R! series) are emerging and there will soon be a very good library of books for using R.

* No license restrictions (other than ensuring our freedom to use it at our own discretion) and so you can run R anywhere and at any time.

* R probably has the most complete collection of statistical functions of any statistical or data mining package. New technology and ideas often appear first in R.

* The graphic capabilities of R are outstanding, providing a fully programmable graphics language which surpasses most other statistical and graphical packages.

* A very active email list, with some of the worlds leading statisticians actively responding, is available for anyone to join. Questions are quickly answered and the archive provides a wealth of user solutions and examples. Be sure to read the Posting Guide first.

* Being open source the R source code is peer reviewed, and anyone is welcome to review it and suggest improvements. Bugs are fixed very quickly. Consequently, R is a rock solid product. New packages provided with R do go through a life cycle, often beginning as somewhat less quality tools, but usually quickly evolving into top quality products.

* R plays well with many other tools, importing data, for example, from CSV files, SAS, and SPSS, or directly from MS/Excel, MS/Access, Oracle, MySQL, and SQLite. It can also produce graphics output in PDF, JPG, PNG, and SVG formats, and table output for LATEX and HTML.

EXAMPLE CODE

SAS CODE

Histogram


R CODE

NOTE: the code in these posts looks sloppy, but if you cut and paste into notepad or the R scripting window it lines up nice

Histogram

Histogram using Schaum's Homework Data (more straightforward than example above)

Kernal Density Plots -

R Code Mean, Variance, Standard Deviation

Selected Practice Problems for Test 1

Regression using R


Plotting Normal Curves and Calculating Probability

Monday, January 4, 2010

Statistics News and Industry

These applications are examples of statistics used in the real world. Many of them may involve more advanced concepts than what we will discuss in class, but my goal is to show you the numerous applications and possibilities with statistics. If you have any questions about anything posted here, don't hesitate to ask.

The new field of Data Science
Applications Using R
Statistics Summary For Media (humor)
For today's graduate just one word: Statistics
Animal Cruelty and Statistical Reasoning
Copulas and the Financial Crisis

Concepts from Mathematical Statistics

A. Concepts from Mathematical Statistics

Probability Density Functions

Random Variables

A random variable takes on values that have specific probabilities of occurring
( Nicholson,2002). An example of a random variable would be the number of car accidents per year among sixteen year olds.

If we know how random variables are distributed in a population, then we may have an idea of how rare an observation may be.

Example: How often sixteen year olds are involved in auto accidents in a year’s time.

This information is then useful for making inferences ( or drawing conclusions) about the population of random variables from sample data.

Example: We could look at a sample of data consisting of 1,000 sixteen year olds in the Midwest and make inferences or draw conclusions about the population consisting of all sixteen year olds in the Midwest.

In summary, it is important to be able to specify how a random variable is distributed. It enables us to gauge how rare an observation ( or sample) is and then gives us ground to make predictions, or inferences about the population.

Random variables can be discrete, that is observed in whole units as in counting numbers 1,2,3,4 etc. Random variables may also be continuous. In this case random variables can take on an infinite number of values. An example would be crop yields. Yields can be measured in bushels down to a fraction or decimal.

The distributions of discrete random variables can be presented in tabular form or with histograms. Probability is represented by the area of a ‘rectangle’ in a histogram
( Billingsly, 1993).

Distributions for continuous random variables cannot be represented in tabular format due to their characteristic of taking on an infinite number of values. They are better represented by a smooth curve defined by a function ( Billingsly, 1993). This function is referred to as a probability density function or p.d.f.

The p.d.f. gives the probability that a random variable ‘X’ takes on values in a narrow interval ‘dx’ ( Nicholson, 2002). This probability is equivalent to the area under the p.d.f. curve. This area can be described by the cumulative density function c.d.f. The c.d.f. gives the value of an integral involving the p.d.f.

Let f(x) be a p.d.f.

P( a <= X <= b ) = a b f(x) dx = F ( x )

This can be interpreted to mean that the probability that X is between the values of ‘a’ and ‘b’ is given by the integral of the p.d.f from ‘a’ to ‘b.’ This value can be given by the c.d.f. which is F ( x ). Those familiar with calculus know that F(x) is the anti-derivative of f(x).


Common p.d.f’s

Most students are familiar with using tables in the back of textbooks for normal, chi-square, t, and F distributions. These tables are generated by the p.d.f’s for these particular distributions. For example, if we make the assumption that the random variable X is normally distributed then its p.d.f. is specified as follows:

f(x)= 1 / (2 ) -1/2 e –1/2 (x - )2/

where X~ N (  )

In the beginning of this section I stated that it was important to be able to specify how a random variable is distributed. Through experience, statisticians have found that they are justified in modeling many random variables with these p.d.f.’s. Therefore, in many cases one can be justified in using one of these p.d.f.’s to determine how rare a sample observation is, and then to make inferences about the population. This is in fact what takes place when you look up values from the tables in the back of statistics textbooks.

Mathematical Expectation

The expected value E(X) for a discrete random variable can be defined as ‘the sum of products of each observation Xi and the probability of observing that particular value of Xi ( Billingsly, 1993). The expected value of an observation is the mean of a distribution of observations. It can be thought of conceptually as an average or weighted mean.

Example: given the p.d.f. for the discrete random variable X in tabular format.

Xi : 1 2 3

P(x =xi) .25 .50 .25


E (X) = Xi P(x =xi) = 1 * .25 + 2*.50 + 3*.25 = 2.0

Conceptually, the expected value of a random variable can be viewed as a point of balance or center of gravity. In reality, the actual value of an observed random variable will likely be larger or smaller than the ‘expected value.’ However due to the nature of the expected value, actual observations will have a distribution that is balanced around the expected value. For this reason the expected value can be viewed as the balancing point for a distribution, or the center of gravity ( Billingsly, 1993).

That is to say that population values cluster or gravitate around the expected value. Most of the population values are expected to be found within a small interval ( i.e. measured in standard deviations) about the population’s expected value or mean. Hence the expected values gives a hint about how rare a sample may be. Values lying near a population mean should not be rare but quite common.

The expected value for a continuous random variable must be calculated using integral calculus.

E(X) = ∫ x f(x) dx

If x is an observed value and f(x) is the p.d.f. for x, then the product x f(x) dx is the continuous version of the discrete case Xi P(x =xi) and integration is the continuous version of summation.

Variance

As I mentioned previously, actual observations will often depart from the expected value. Variance quantifies the degree to which observations in a distribution depart from an expected value. It is a mean of squared deviations between an observation and an expected value/mean (Billingsly, 1993).

In the discrete case we have the following mathematical description:

X -  )2 = 2

In the continuous case:

∫ (X -  )2 f(x) dx = E( X -  ) = 2


Given the mean (), or expected value of a random variable, one knows the value a random variable is likely to assume on average. The variance (2) indicates how close these observations are likely to be to the mean or expected value on average.




Sample Estimates

Given knowledge of the population mean and variance, one can characterize the population distribution for a random variable. As I mentioned at the beginning of the previous section, it is important to be able to specify how a random variable is distributed. It enables us to gauge how rare an observation ( or sample) is and then gives us grounds to make predictions, or inferences about the population.

It is not always the case that we have access to all of the data from a population necessary for determining population parameters like the mean and variance. In this case we must estimate these parameters using sample data to compute estimators or statistics.

Estimators or statistics are mathematical functions of sample data. The approach most students are familiar with in computing sample statistics is to compute the sample mean ( Xbar) and sample variance (s2) from sample data to estimate the population mean () and variance (2). This is referred to as the analogy principle, which involves using a corresponding sample feature to estimate a population feature (Bollinger,2002).


Properties of Estimators

A question seldom answered in many undergraduate statistics or research methods courses is how do we justify computing a sample mean from a small sample of observations, and then use it to make inferences about the population?

I have discussed the fact that most of the values in a population can be expected to be found within a small interval about the population mean or expected value. The question remains to be can we expect that most of the values of a population observation be found within a small interval of a sample mean? This must be true if we are to make inferences about the population using sample data and estimators like the sample mean.

Just like random variables, estimators or statistics have distributions. The distributions of estimators/statistics are referred to as sampling distributions. If the sampling distribution of a statistic is similar to that of the population then it may be useful to use that statistic to make inferences about the population. In that case sample means and variances may be good estimators for population means and variances.

Fortunately statisticians have developed criteria for evaluating ‘estimators’ like the sample mean and variance. There are four properties that characterize good estimators.




Unbiased Estimators

If ^ is an estimator for the population parameter , and if
E (^ then ^ is an unbiased estimator of the population parameter . This implies that the distribution of the sample statistic/estimator is centered around the population parameter ( Bollinger, 2002).

Consistency

^ is a consistant estimator of  if

lim as n infinity : Pr[ | ^ -  | < c ] = 1

This implies that as you add more and more data, the probability of getting closer and closer to  gets large or variance of ^ approaches zero as n approaches infinity. It can be said that ^ p  or converges in probability to  (Bollinger, 2002).

Efficiency

This is based on the variance of the sample statistic/estimator. Given the estimator ^, and an alternative estimator ~, ^ is more efficient given that

Variance(^) < Variance(

Mean Squared Error is a method of quantifying efficiency.

MSE = E [ [ - ^]2] = V(^) + E[ (E(^) - )]2 = variance + bias squared.

It can then be concluded that for an unbiased estimator the measure of efficiency reduces to the variance (Bollinger, 2002).

Robustness

Robustness is determined by how other properties ( i.e. unbiasedness,consistency,efficiency,) are affected by assumptions made
(Bollinger, 2002).

When sample statistics or estimators exhibit these four properties, statisticians feel that they can rely on these computations to estimate population parameters. It can be shown mathematically that the formulas used in computing the sample mean and variance meet these criteria.






Confidence Intervals

Confidence intervals are based on the sampling distributions of a sample statistic/estimator. Confidence intervals based on these distributions tell us what values an estimator ( ex: the sample mean) is likely to take, and how likely or rare the value is ( DeGroot, 2002). Confidence intervals are the basis for hypothesis testing.

Theoretical Confidence Interval

If we assume that our sample data is distributed normally, Xi ~ N (2) then it can be shown that the statistic

Z = ( Xbar - )2 / (2 / n)1/2 ~ N( 0, 1) Standard Normal Distribution ( Billingsly, 1993).

Given the probabilities represented by the standard normal distribution it can be shown as a matter of algebra that

Pr ( -1.96 <= Z <= 1.96) = .95

The value 1.96 is the qauntile of the standard normal distribution such that there is only a .025 or 2.5% chance that we will find a Z value greater than 1.96. Conversely there is only a 2.5% chance of finding a computed Z value less than –1.96
( Steele, 1997).

As a matter of algebra it can be shown that


Pr(Xbar - 1.96 (2 / n)1/2 <= <= Xbar + 1.96 (2 / n)1/2 ) = .95

( Goldberger, 1991).

This implies that 95% of the time we can be confident that the population mean will be 1.96 standard deviations from the sample mean. The interval above then represents a 95% confidence interval ( Bollinger, 2002).


The Central Limit Theorem –Asymptotic Results

The above confidence interval is referred to as a Theoretical confidence interval. It is theoretical because is based on knowledge of the population distribution being normal. According to the central limit theorem:

Given random sampling, E(X) = , V(X) = 2 , the Z- statistic Z = ( Xbar - )2 / (2 / n1/2) converges in distribution to N( 0,1). That is


( Xbar - )2 / (2 / n1/2) ~A N(0,1)

It can then be stated that the statistic is asymptotically distributed standard normal.
Asymptotic properties are characteristics that hold as the sample size becomes large or approaches infinity. The CLT holds regardless of how that sample data is distributed, hence there are no assumptions about normality necessary (DeGroot 2002).

Student’s t Distribution-Exact Results

A limitation of the central limit theorem is that it requires knowledge of the population variance. In many cases we use s2 to estimate 2 . Gosset, a brewer for Guiness in the 1800’s was interested in normally distributed data with small sample sizes. He found that using Z with s2 to estimate 2 did not work well with small samples. He wanted a statistic that relied on exact results vs. large sample asymptotics ( Steele, 1997).

Working under the name Student, he developed the t distribution, where

t = ( Xbar - )2 / (s2 / n)1/2 ~ t(n-1)


The t distribution is the ratio of a normally distributed variable and chi-square distributed variable ( DeGroot, 2002). It is important to note that the central limit theorem does not apply because we are using s2 instead of 2. Here we can rely on using the t-table for constructing confidence intervals and rely on exact results vs. the approximate or asymptotic results of the
CLT ( DeGroot, 2002).

More Asymptotics- Extending the CLT

Sometimes we don’t know the distribution of the data we are working with, or don’t feel comfortable making assumptions of normality. Usually we have to estimate 2 with s2 . In this case we can’t rely on the asymptotic results of the CLT or the exact results of the t-distribution.

In this case there are some powerful theorems regarding asymptotic properties of sample statistics known as the Slutsky Theorems.

Tuesday, October 27, 2009

10 Principles Rap

Hear the 10 Principles of Macroeconomics- Rap Version

Source : Your Textbook Author's Blog



Demand, Supply - Rhythm, Rhyme, Results ( Click for full version including all 10 Principles below)


10 Principles of Economics: Gregory Mankiw, Brief Principles of Macroeconomics 5th edition

1. People Face Tradeoffs. To get one thing, you have to give up something else. Making decisions requires trading off one goal against another.

2. The Cost of Something is What You Give Up to Get It. Decision-makers have to consider both the obvious and implicit costs of their actions.

3. Rational People Think at the Margin. A rational decision-maker takes action if and only if the marginal benefit of the action exceeds the marginal cost.

4. People Respond to Incentives. Behavior changes when costs or benefits change.

5. Trade Can Make Everyone Better Off. Trade allows each person to specialize in the activities he or she does best. By trading with others, people can buy a greater variety of goods or services.

6. Markets Are Usually a Good Way to Organize Economic Activity. Households and firms that interact in market economies act as if they are guided by an "invisible hand" that leads the market to allocate resources efficiently. The opposite of this is economic activity that is organized by a central planner within the government.

7. Governments Can Sometimes Improve Market Outcomes. When a market fails to allocate resources efficiently, the government can change the outcome through public policy. Examples are regulations against monopolies and pollution.

8. A Country's Standard of Living Depends on Its Ability to Produce Goods and Services. Countries whose workers produce a large quantity of goods and services per unit of time enjoy a high standard of living. Similarly, as a nation's productivity grows, so does its average income.

9. Prices Rise When the Government Prints Too Much Money. When a government creates large quantities of the nation's money, the value of the money falls. As a result, prices increase, requiring more of the same money to buy goods and services.

10. Society Faces a Short-Run Tradeoff Between Inflation and Unemployment. Reducing inflation often causes a temporary rise in unemployment. This tradeoff is crucial for understanding the short-run effects of changes in taxes,government spending and monetary policy.

Saturday, October 24, 2009

Campus Sustainability Day and Economic Growth

This past Wednesday was campus sustainability day. In light of that, we can see how the lessons we have learned about technological change economic growth apply to the sustainable use of resources.

One place to see this is on the family farm. We often get the idea from the media that our food industry has been taken over by industrial farms, but the numbers just don't support those notions. Family farms make up 98% of all farms in the U.S. and according to the USDA ERS (2007) non family corporations make up less than 1% of the total number of farms in the U.S. and have accounted for only 6-7% of farm product sales in every census since 1978.

See the following videos to learn more about the technology that is fueling the growth in sustainable agriculture today.










Additional Information:

Structure and Finances of U.S. Farms: Family Farm Report, 2007 USDA ERS

GM crops: global socio-economic
and environmental impacts 1996-
2007 PG Economics (link)

The Environmental Safety and Benefits of Growth Enhancing Pharmaceutical Technologies in Beef Production
By Alex Avery and Dennis Avery, Hudson Institute, Centre for Global Food Issues.

Capper, J. L., Cady, R. A., Bauman, D. E. The environmental impact of dairy production: 1944 compared with 2007. Journal of Animal Science, 2009; 87 (6): 2160 DOI: 10.2527/jas.2009-1781

New York Times Don't Cry Over rBST Milk June 29, 2007

MSN Health and Fitness Bovine Growth Hormone

Dr. Harlan Ritchie, Michigan State University. How safe is our product Beef?

Doyle et al., Institute of Food Technologists, “Antimicrobial Resistance: Implications for the Food System” Comprehensive Reviews in Food Science and Food Safety, Vol.5, Issue 3, 2006

Sandiego Center for Molecular Agriculture Foods from Genetically Modified Crops ( pdf)

Tuesday, October 6, 2009

Income, Poverty and Economic Growth






New York Times: You Are What You Spend-

"Income statistics, however, don’t tell the whole story of Americans’ living standards. Looking at a far more direct measure of American families’ economic status — household consumption — indicates that the gap between rich and poor is far less than most assume, and that the abstract, income-based way in which we measure the so-called poverty rate no longer applies to our society."

Wall Street Journal: Income Mobility- U.S. Treasury Study (link)



"The Treasury study examined a huge sample of 96,700 income tax returns from 1996 and 2005 for Americans over the age of 25. The study tracks what happened to these tax filers over this 10-year period. One of the notable, and reassuring, findings is that nearly 58% of filers who were in the poorest income group in 1996 had moved into a higher income category by 2005. Nearly 25% jumped into the middle or upper-middle income groups, and 5.3% made it all the way to the highest quintile.\"

Income Mobility in the U.S. from 1996 to 2005
Report of the
DEPARTMENT OF THE TREASURY

"Economic growth resulted in rising incomes for most taxpayers over the period from 1996 to 2005. Median incomes of all taxpayers increased by 24 percent after adjusting for inflation. The real incomes of two-thirds of all taxpayers increased over this period. In addition, the median incomes of those initially in the lower income groups increased more than the median incomes of those initially in the higher income groups. The degree of mobility in the overall population and movement out of the bottom quintile in this study are similar to the findings of prior research on income mobility."

From the PEW Economic Mobility Studies:

http://cafehayek.com/2009/06/absolute-mobility.html 





  Source: The Myth of Middle-Class Stagnation, Steve Conover


From the October 3rd EconTalk podcast, Bruce Meyer discusses income inequality since the 1960's:

"Bruce Meyer of the University of Chicago talks with EconTalk host Russ Roberts about the middle class, poverty, and inequality. Many economists and pundits argue that the middle class has made little or no economic progress over the last 30 years, that poverty rates are stagnant or rising, and that inequality has increased dramatically. Meyer, drawing on his research over the last ten years, argues that these conclusions are either false or misleading. He argues that standard measures of economic progress and inequality are based on faulty inflation data or a misplaced focus on pre-tax income instead of post-tax income or consumption. " 

Some excerpts from Meyer's paper:

Consumption and Income Inequality in the U.S. Since the 1960s*
October 18, 2010
Bruce D. Meyer
University of Chicago and NBER
and James X. Sullivan
University of Notre Dame


http://harrisschool.uchicago.edu/faculty/web-pages/Inequality60s.pdf 
"Income data primarily come from the ASEC/ADF Supplement to the Current Population Survey (CPS), which is the source for official measures of poverty and inequality in the U.S. We use data from the 1964-2006 surveys which provide data on income for the previous
calendar year."
What we see is that compare the top 10% (90th percentile)to the bottom 10% the ratio o inequality (income for the top 10% / income for the bottom 10%) has increased very little. Adjusting for taxes, the ratio has went from about 5.5 to about 6.25, while adjusting for taxes and transfers, it has increased from about 4.10 to about 5.75. We don't see drastic changes such as a 10 fold change or even a doubling of the gap as the media might impress. Looking at just the last 10-15 years, the change is even smaller. 
If we look at the top 10% of earners vs. the median earners, (often the most popular claims in the is  that the gap between median income earners and the top earners has gotten larger as median income has stagnated over the last 30 years) we see that the ratio has remained changed very little since 1961, going from around 2.0 to about 2.25 adjusting for taxes and transfers, and has been even flatter since the 90's.
Finally, when compare the median income earners to the bottom 10%, again we find little change in income differences since 1961. There was a growing gap for a period during the 1980's, but those slight increases diminished in the 90's and we finished out 2007 at a ratio right about 2.5 where we started in 1961. 


 As Bruce Meyer's work above indicates, you can't just take income related data at face value. If we look at income inequality based on family market income data used by Picketty and Saez teh picture looks pretty bleak:


Saez, Emmanuel. (2012). Striking it Richer: The Evolution of Top Incomes in the United States. (Updated with 2009 and 2010 estimates). http://elsa.berkeley.edu/~saez/saez-UStopincomes-2010.pdf





 However, there are huge differences in outcomes when we consider how we measure income a well as how we account for things like household economies of scale:



"A Second Opinion on the Economic Health of the American Middle Class and Why it Matters in Gauging the Impact of Government Policy," by Richard V. Burkhauser, Jeff Larrimore and Kosali Simon. National Tax Journal, March 2012.

“Researchers considering levels and trends in the resources available to the middle class traditionally measure the pre-tax cash income of either tax units or households. In this paper, we demonstrate that this choice carries significant implications for assessing income trends. Focusing on tax units rather than households greatly reduces measured growth in middle class income. Furthermore, excluding the effect of taxes and the value of in-kind benefits further reduces observed improvements in the resources of the middle class. Finally, we show how these distinctions change the observed distribution of benefits from the tax exclusion of employer provided health insurance”



 For more details about this methodology, see the April 9,2012 EconTalk podcast with Burkhauser:
http://www.econtalk.org/archives/2012/04/burkhauser_on_t.html



CNN Money - CEO Pay

From: http://www.epi.org/publication/webfeatures_snapshots_20060621/ 






When considering income, how might the marginal contribution (in terms of the value of output, consumer surplus etc.)  of a CEO vs. the average worker changed over time? Were there changes in capital (which complements labor)? What about the size of the market served by new products?

You can find a very good discussion of these issues from a Cato Daily Podcast here: Steve Jobs, Profit and Social Obligation