Docsity

Data Analysis in Sociological Research: Simulating Random Samples and Probability Models, Exercises of Advanced Data Analysis

Toggle sidebar
bg1
University of North Carolina
Chapel Hill
Soci252-003 Data Analysis in Sociological
Research
Spring 2012
Professor François Nielsen
Homework 3 – Computer Handout
1 Readings
This handout covers computer issues related to Chapters 11, 12, 13, 14, 15, 16 and 17 in De
Veaux et al. 2012. Stats: Data and Models. 3e. Addison-Wesley. (STATDM3)
2 Chapter 11 – Simulation
2.1 Random Generating Functions
All distribution functions in R can be used with the r- prefix to generate a set of random
number from the distribution. For example, to generate a random sample of 100 numbers
from a standard normal distribution one can use the following command. I first set rseed to a
known value to make the results reproducible. As a sample of 100 is relatively small I can use
a stem and leaf plot to look at the distribution; for a substantially larger sample I would use a
histogram instead.
> rseed <- 414
> nor <- rnorm(100)
> head(nor)
[1] 0.9071645 0.8173079 -1.6079584 0.9977253 -0.4575953 -0.2676742
> stem(nor)
The decimal point is at the |
-2 | 972
-1 | 996553332221100000
-0 | 999988877766666554443333222100000
0 | 011111122222333333344455567788888999
1 | 011245688
2|5
To simulate the number of births of female babies in 200 births in a certain hospital one can use
the function rbinom (the name of which is the combination of the r- prefix indicating a random
generator with the binomial distribution stem -binom). The probability that a baby is a girl or a
boy is 48.8% and 51.2%, respectively. The following command produces one simulation of the
number of girls in 200 births.
1
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Data Analysis in Sociological Research: Simulating Random Samples and Probability Models and more Exercises Advanced Data Analysis in PDF only on Docsity!

University of North Carolina Chapel Hill

Soci252-003 Data Analysis in Sociological

Research

Spring 2012

Professor François Nielsen

Homework 3 – Computer Handout

1 Readings

This handout covers computer issues related to Chapters 11, 12, 13, 14, 15, 16 and 17 in De Veaux et al. 2012. Stats: Data and Models. 3e. Addison-Wesley. (STATDM3)

2 Chapter 11 – Simulation

2.1 Random Generating Functions

All distribution functions in R can be used with the r- prefix to generate a set of random number from the distribution. For example, to generate a random sample of 100 numbers from a standard normal distribution one can use the following command. I first set rseed to a known value to make the results reproducible. As a sample of 100 is relatively small I can use a stem and leaf plot to look at the distribution; for a substantially larger sample I would use a histogram instead.

> rseed <- 414 > nor <- rnorm(100) > head(nor) [1] 0.9071645 0.8173079 -1.6079584 0.9977253 -0.4575953 -0. > stem(nor)

The decimal point is at the |

To simulate the number of births of female babies in 200 births in a certain hospital one can use the function rbinom (the name of which is the combination of the r- prefix indicating a random generator with the binomial distribution stem -binom). The probability that a baby is a girl or a boy is 48.8% and 51.2%, respectively. The following command produces one simulation of the number of girls in 200 births.

> ngirls <- rbinom(1, 200, .488) > ngirls [1] 92

The function call rbinom(1, 200, .488) means “return the number of female births in 1 randomly generated sample of 200 births for which the probability of a girl is .488”. The number of baby girls is 92 in this sample. To get a sense of the distribution of the number of girls in 200 births we can repeat the simulation 100 times, using the table function to summarize the outcome.

> ngirls <- rbinom(100, 200, .488) > head(ngirls) [1] 106 105 99 111 92 98 > table(ngirls) ngirls 79 83 85 86 87 88 89 90 91 92 93 94 95 96 97 98 1 1 1 1 1 3 4 2 6 4 3 1 5 8 4 5 99 100 101 102 103 104 105 106 107 108 109 110 111 113 120 6 9 1 10 2 5 3 3 3 1 1 1 3 1 1

We see that there is substantial variation among the 100 simulations, with the number of girls varying from a minimum of 79 to a maximum of 120.

2.2 The sample Function

The function sample selects random samples from any vector. To illustrate I show how to im- plement the textbook example of a cereals producer randomly inserting pictures of sports stars LeBron James, David Beckham and Serena Williams in boxes of cereals in proportions 20%, 30% and 50%, respectively. The following code shows how to create a vector pictures containing the names, and then sample one name from that vector with the specified probabilities.

> pictures <- c("LeBron", "Beckham", "Serena") > sample(pictures, 1, replace = TRUE, p = c(0.2, 0.3, 0.5)) [1] "LeBron"

To get a sense of the distribution of the draws, I repeat the draw 100 times (equivalent to buying and then opening 100 boxes of cereals!), storing the results in vector pic100, looking at the first 6 draws with the head function, and then summarizing the simulation using the table function.

> pic100 <- sample(pictures, 100, replace = TRUE, p = c(0.2, 0.3, 0.5)) > head(pic100) [1] "Beckham" "Serena" "Serena" "Beckham" "Serena" "LeBron" > table(pic100) pic Beckham LeBron Serena 27 15 58

Over the 100 draws the simulated proportions of .15, .27 and .58 for LeBron, Beckham and Serena are fairly close to the expected proportions .20, .30 and .50. (Note however that the table function lists the names in alphabetical order, not the order in which I originally entered them in pictures.)

  • n <- 0
  • tally <- c(0, 0, 0)
  • while (sum(tally)<3){
  • tally[sample(1:3, 1, replace = TRUE, p = c(0.2, 0.3, 0.5))] <- 1
  • n <- n + 1 }
  • n.boxes[s] <- n } > table(n.boxes) n.boxes 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 169 175 169 131 58 75 37 31 36 28 15 12 13 15 5 4 7 2 2 3 23 24 26 30 32 35 37 2 4 2 1 2 1 1 > hist(n.boxes)

The tabulation of the 1000 trials shows that 3 is the minimum number of boxes opened. Three boxes were enough to get the entire collection of pictures in 16.9% of trials; four boxes were needed in 17.5% of trials, etc. The histogram (Figure 1) shows that the distribution of number of boxes is highly skewed. In one trial 37 boxes had to be opened to get the entire collection of three pictures!

Histogram of n.boxes

n.boxes

Frequency

0 10 20 30 40

0

100

200

300

400

500

Figure 1: Histogram of the simulated number of boxes of cereals opened to secure the complete collection of pictures of LeBron, Beckham and Serena (1000 trials).

Problem 17 p.278 The results of opening 5 cereal boxes 1000 times can be simulated with the following R code.

> n.sims <- 1000 > complete <- rep(FALSE, n.sims) # vector of logical values > for (s in 1:n.sims) {

  • tally <- c(0, 0, 0)
  • for (i in 1:5) {
  • tally[sample(1:3, 1, replace = TRUE, p = c(0.2, 0.3, 0.5))] <- 1 }
  • complete[s] <- sum(tally) >= 3 } > table(complete)

(Output not shown.) The desired probability is the proportion of TRUE values of complete. We could also have estimated that probability by adding up the probabilities of 3, 4, and 5 boxes in the previous simulation example.

2.4 Simulation with replicate

I use the data set depress of Afifi and Clark to simulate a typical survey drawing a simple random sample without replacement from a population. I previously downloaded the file depress.dta from the site http://www.ats.ucla.edu/stat/Splus/examples/cama4/ and saved it in my work directory. Since the file is in Stata format I load the library foreign, which provides a function read.dta to read Stata data files. After attaching the file, I calculate summary statistics and draw a histogram of the variable cesd.

> # Afifi and Clark data > library(foreign) > depress <- read.dta("depress.dta") > attach(depress) > summary(cesd) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.000 3.000 7.000 8.884 12.000 47. > sd(cesd) [1] 8. > hist(cesd)

Histogram of cesd

cesd

Frequency

0 10 20 30 40 50

0

20

40

60

80

100

120

Figure 2: Histogram of CESD scores in Afifi and Clark’s depress data (N = 294).

The depress file contains data from a community survey of about 300 respondents in a neigh- bourhood of Southern California. Among the variables is cesd, which is the respondent’s score on a well known scale of depressive symptoms. The cesd scale is constructed by summing scores on twenty questionnaire items, each coded from 0 to 3, so the theoretical range is be- tween 0 and 60. The descriptive statistics show that the actual maximum value in the data is 47; the median is 7 and the mean is 8.884. The histogram (Figure 2) indicates a skewed distribution with a concentration of observations around zero (i.e., no depressive symptoms). The sample function can be used to draw a simple random sample of size 10 from the data set, as follows.

> # sampling 10 observations from cesd population > sample(cesd, 10, replace=FALSE)

> sd(sim100) [1] 0. > hist(sim100) > detach(depress)

Histogram of sim

sim

Frequency

7 8 9 10 11

0

20

40

60

80

100

120

140

Figure 4: Histogram of the mean CESD scores for 600 simple random samples of 100 observa- tions from Afifi and Clark’s depress data.

The histogram of Figure 4 exhibits a high degree of symmetry. The mean of the 600 samples is 8.862 (close to the population mean of 8.884) and the standard deviation of the sample means is .751, smaller than the standard deviation of the 600 samples of 10 (2.737), and actually somewhat smaller than 8.824 /

p 100 = .882; we will explain this phenomenon later.^1

3 Chapter 12 – Sample Surveys

See previous section on using the sample function to draw a random sample from a sampling frame. See STATSDM3 p.300 on an equivalent method of drawing a random sample when the sample function is not available.

4 Chapter 13 – Experiments and Observational Studies

See STATSDM3 p.325.

5 Chapter 14 – From Randomness to Probability

There are no specific software issues for this chapter.

6 Chapter 15 – Probability Rules!

There are no specific software issues for this chapter.

(^1) This is due to the fact that the samples of 100 are large (more than 10%) relative to the total size of the population (294). As a result ¯ x is more precise (closer to μ ) than we would expect on the basis of the sample size alone.

7 Chapter 16 – Random Variables

See STATSDM3 p.398–399. For operations such as calculating mean and variance of random variables R can simply be used as a calculator.

8 Chapter 17 – Probability Models

Functions for the binomial, geometric and Poisson probability models are discussed in general in STATSDM3 p.419–421. R has the full complement of functions for these probability models, irrespective of the size of the problem. The most frequently used functions are the following. In the discussion below pdf stands for “probability density function”, and cdf stands for “cumulative distribution function”.

Geometric pdf dgeom(x-1, prob) finds the individual geometric probability of getting the first success on trial x when the probability of success is prob.^2 For example, the probability of finding the first LeBron James picture in the fifth cereal box (i.e., experiencing 4 failures before success on trial 5) is

> dgeom(5-1, .2) [1] 0.

Geometric cdf pgeom(x-1, prob) finds the cumulative probability of getting the first success on or before trial x, when the probability of success is prob. For example, the total probability of finding LeBron’s picture in one of the first 4 boxes is

> pgeom(4-1, .2) [1] 0.

Binomial pdf dbinom(x, n, prob) finds the probability of getting x successes in n trials when the probability of success is prob. For example, the probability of finding LeBron’s picture exactly twice among 5 boxes of cereals is

> dbinom(2, 5, 0.2) [1] 0.

Poisson pdf dpois(x, lambda) finds the probability of x successes when the mean number of successes is lambda = np. The Poisson model is best for large n and small probability of success. For example, the probability of finding exactly 3 cases of leukemia in Woburn, given that the population is n = 35, 000 and the national probability of a new case each year is p = 0.00011 so that λ = np = 3.85, is

> dpois(3, 3.85) [1] 0. (^2) The number of trials has to be entered as x-1 rather than x because pgeom in R is defined in terms of “the number of failures in a sequence of Bernoulli trials before success occurs”. So, for example, the probability of finding LeBron on the first trial (i.e., zero failure beforehand) is given by dgeom(0, .2) = .2. The same convention is used for pgeom.