MATH 6627 2010-11 Practicum in Statistical Consulting/Assignment Teams/Gray

From Wiki1

Jump to: navigation, search
 
(75 intermediate revisions not shown)
Line 6: Line 6:
Example: My friend and I play a basketball game and each shoot 20 shots. Who is the better shooter?
Example: My friend and I play a basketball game and each shoot 20 shots. Who is the better shooter?
-
[[File:h65.PNG]]
+
[[File:h65.PNG|150px]]
But, who is the better shooter if you control for the distance of the shot?  Who would you rather have on your team?
But, who is the better shooter if you control for the distance of the shot?  Who would you rather have on your team?
-
[[File:h32.PNG]]
+
[[File:h32.PNG|150px]]
This is question of Simpson's Paradox.  
This is question of Simpson's Paradox.  
-
[[File:h45.PNG]]  
+
[[File:h45.PNG|150px]]  
We can see from this figure, the relationship changed from negative to positive when we took the distance to our consideration. Black line linked probability of we two made. Red line is linked our performance when far, but blue when close.
We can see from this figure, the relationship changed from negative to positive when we took the distance to our consideration. Black line linked probability of we two made. Red line is linked our performance when far, but blue when close.
Line 41: Line 41:
With ''rgl'' we create a ‘device’ , which is simply a window, within which a ‘world’ is created where we can create 3 dimensional shapes and through which we can navigate.
With ''rgl'' we create a ‘device’ , which is simply a window, within which a ‘world’ is created where we can create 3 dimensional shapes and through which we can navigate.
-
[[File:Grey_World.png|200px]]
+
[[File:Grey_World.png|150px]]
Functions within the rgl package can be divided into 6 categories:
Functions within the rgl package can be divided into 6 categories:
Line 49: Line 49:
(4) Shape functions - essential plotting tools primitives (points, lines, triangles, quads) as well as higher level functions (text, spheres, surfaces).
(4) Shape functions - essential plotting tools primitives (points, lines, triangles, quads) as well as higher level functions (text, spheres, surfaces).
-
[[File:Grey-Shapes.png]]
+
[[File:Grey-Shapes.png|150px]]
(5) Environment functions - modify the viewpoint, background and bounding box, adding light sources
(5) Environment functions - modify the viewpoint, background and bounding box, adding light sources
(6) Appearance function rgl.material(…).
(6) Appearance function rgl.material(…).
-
[[File:Grey_AppearanceOptions.png|300px]]
+
[[File:Grey_AppearanceOptions.png|150px]]
Using shapes and surfaces within an ''rgl'' device, statistical data can be represented in 3 dimensions. Some advanced examples are available as demos or provided on the [http://rgl.neoscientists.org/docs.shtml rgl website].
Using shapes and surfaces within an ''rgl'' device, statistical data can be represented in 3 dimensions. Some advanced examples are available as demos or provided on the [http://rgl.neoscientists.org/docs.shtml rgl website].
-
[[File:Gray_Rgl_3d_histogram.png|200px]]
+
[[File:Gray_Rgl_3d_histogram.png|150px]]
-
[[File:Grey_rgl_example_imulated_animal_abundance.png|200px]]
+
[[File:Grey_rgl_example_imulated_animal_abundance.png|150px]]
A few of the functions from ''rgl'' are useful for manipulating 3D models created using ''p3d'', since ''p3d'' contains many functions that inherit from ''rgl'' but taylor them to statistical methods. Thus all but a few are unnecessary for our purposes unless you would like to contribute functionality to ''p3d''!
A few of the functions from ''rgl'' are useful for manipulating 3D models created using ''p3d'', since ''p3d'' contains many functions that inherit from ''rgl'' but taylor them to statistical methods. Thus all but a few are unnecessary for our purposes unless you would like to contribute functionality to ''p3d''!
Line 93: Line 93:
We can remove elements from the device using the function ''Pop3d()''. This function removes elements starting with the most recently added item. Multiple items can be removed addition an numeric argument, ie.''Pop3d(4)''<br>
We can remove elements from the device using the function ''Pop3d()''. This function removes elements starting with the most recently added item. Multiple items can be removed addition an numeric argument, ie.''Pop3d(4)''<br>
-
[[File:Gray_rgl_navigation.png|200px]]
+
[[File:Gray_rgl_navigation.png|150px]]
-
[[File:Gray_p3d_ex1.png|200px]]
+
[[File:Gray_p3d_ex1.png|150px]]
----
----
Init3d(cex = .8)<br>
Init3d(cex = .8)<br>
Line 102: Line 102:
Next we will subdivide the data by category, in this case whether the school is private (red) or public (blue) (variable name public.private).<br>
Next we will subdivide the data by category, in this case whether the school is private (red) or public (blue) (variable name public.private).<br>
-
[[File:Gray_p3d_ex2.png|200px]]
+
[[File:Gray_p3d_ex2.png|150px]]
----
----
Init3d(cex = .8)<br>
Init3d(cex = .8)<br>
Line 110: Line 110:
Next we will add regression planes for private(red) and public(blue) schools using the lm() function to determine the fit, and Fit3d() to insert the plane in the graph.  Axes and labels are added using Axes3d() and title3d().<br>
Next we will add regression planes for private(red) and public(blue) schools using the lm() function to determine the fit, and Fit3d() to insert the plane in the graph.  Axes and labels are added using Axes3d() and title3d().<br>
-
[[File:Gray_p3d_ex3.png]]
+
[[File:Gray_p3d_ex3.png|150px]]
----
----
fitpub = lm(tuition ~ fac_comp + graduat,subset=(public.private==0),data = tuit)<br>
fitpub = lm(tuition ~ fac_comp + graduat,subset=(public.private==0),data = tuit)<br>
Line 124: Line 124:
Data ellipses are useful for understanding our data.<br>
Data ellipses are useful for understanding our data.<br>
-
[[File:Gray_p3d_ex4.png]]
+
[[File:Gray_p3d_ex4.png|150px]]
----
----
Ell3d()
Ell3d()
Line 132: Line 132:
We can change the view point of our graph using function ''view3d(theta,phi,fov,zoom)'', which takes polar coordinates.  Note that ''view3d(0,0,0)'' will rotate the image to to face the x-z plane (y into the screen) and  ''view3d(270,0,0)'' will rotate the image to to face the y-z plane (x into the screen).  Function ''snap()'' will capture a still image of the current view. Note that to use ''movie3d()'' you must have ImageMagick installed to automatically convert png's to gif, otherwise you must use external software.
We can change the view point of our graph using function ''view3d(theta,phi,fov,zoom)'', which takes polar coordinates.  Note that ''view3d(0,0,0)'' will rotate the image to to face the x-z plane (y into the screen) and  ''view3d(270,0,0)'' will rotate the image to to face the y-z plane (x into the screen).  Function ''snap()'' will capture a still image of the current view. Note that to use ''movie3d()'' you must have ImageMagick installed to automatically convert png's to gif, otherwise you must use external software.
-
[[File:Gray_p3d_ex5.png]]
+
[[File:Gray_p3d_ex5.png|150px]]
-
[[File:GrayMovie.gif‎]]
+
[[File:GrayMovie.gif]]
----
----
view3d(0,0,0)<br>
view3d(0,0,0)<br>
Line 147: Line 147:
Here is an additional example, using data on the US indices of industrial products, plotting Mining production (MIN) over months and years.  Adding the argument ‘groups=YR’ to ''Plot3d'' connects the months in a given year to produce trajectories.
Here is an additional example, using data on the US indices of industrial products, plotting Mining production (MIN) over months and years.  Adding the argument ‘groups=YR’ to ''Plot3d'' connects the months in a given year to produce trajectories.
-
[[File:Gray_p3d_ex6.png]]
+
[[File:Gray_p3d_ex6.png|150px]]
----
----
open3d(windowRect=c(100,100,800,800),cex = .8) <br>
open3d(windowRect=c(100,100,800,800),cex = .8) <br>
Line 161: Line 161:
==Assignment 2==
==Assignment 2==
-
Statistics in the News: "Spousal support a royal pain?"
+
Statistics in the News: "Spousal support a royal pain?" [http://journals.lww.com/clinicalpain/Abstract/2003/07000/Spousal_Responses_Are_Differentially_Associated.4.aspx Journal Abstract]
 +
 
 +
Overly supportive spouses are not necessarily doing their partners a favour.
 +
 
 +
''They could be prolonging the recovery of their injured spouses.''
 +
 
 +
Men with highly attentive spouses reported higher levels of pain and more disability but did well on physical functions tests.
 +
 
 +
Women with highly attentive spouses didn't report feeling more pain or being more disabled. However, they performed more poorly on physical function tests than did women with less attentive spouses
 +
 
 +
[[MEDIA: Gray_RoyalPain.pdf]]
====1====
====1====
Line 167: Line 177:
;Discussion:  
;Discussion:  
 +
Yes, the article did suggest a causal relationship. One variable is the spousal solicitousness (attentiveness & support). Another is the degree of reported pain and disability. A third is actual physical function. Patient gender was also taken into consideration.
 +
 +
According to the report, men with chronic pain report more perceived pain and disability when they receive higher levels of spousal attention, and it is implied this is controlling for actual physical ability. For women there was no difference in self-reports of pain and disability with level of spousal support, but women who received more attention from their husbands had poorer physical function than those who did not.
 +
 +
The data are observational, because there is no manipulation or randomization in collecting the data.
 +
====2====
====2====
Line 172: Line 188:
;Discussion:  
;Discussion:  
 +
Andy: Yes, maybe high degree of pain causes solicitousness, instead of solicitousness causing towards more pain. I don't think there exits a confounding factor. If there is, I believe it is LOVE, because a man's LOVE wins a highly attentive spouse and doesn't work as a narcotic as a woman feels. Then he may ask for more LOVEs by reporting hurt. That is a sweet answer to any woman, but tooth-hurting felt by any healthy man.
 +
Also, LOVE could be the mediating factor too. And with high solicitousness, man's LOVE starts to fall in. He may move his body, more likely, which may cause more hurt. And then his physical function may recover faster. But to a woman, she likes to finding pieces of LOVEs through solicitousness. Her heart is numbed with those LOVEs. And then she will report she is better as an affectionate payback.
 +
   
====3====
====3====
;Question: Have any confounding factors been accounted for in the analysis?  
;Question: Have any confounding factors been accounted for in the analysis?  
;Discussion:  
;Discussion:  
 +
 +
Emotional (men) or Physical (women) troubles outside the primary cause of pain.  Men who are emotionally unstable may attract and encourage attentiveness in their wives, and also report a disproportionately high level of disability relative to their level of function. Women who are physically weak prior to injury may attract husbands who are highly supportive, but also be more susceptible to injuries that result in chronic pain.
====4====
====4====
Line 182: Line 203:
;Discussion:  
;Discussion:  
 +
 +
This does not appear to be the case.
====5====
====5====
Line 187: Line 210:
;Discussion:  
;Discussion:  
 +
 +
There is a good case to be made for both forward and backward causality in this study. In addition it would be nice to be able to ontrol for emotional and physical stability prior to chronic injury.
 +
Are frequencies distributed as expected? Are the proportions of highly attentive spouses equal across groups?
 +
ASSESSMENT: Judgement withheld pending further evidence
Line 195: Line 222:
;Discussion:  
;Discussion:  
 +
True.  It is more important to accurately measure Coffee Consumption if this is the variable of primary interest in the study. 
 +
 +
Consider this from the analysis of variance framework.  When measurement error is introduced, the variability in the outcome accounted for by that factor is decreased, and the error sums of squares increases.  If we decrease accuracy in measuring Stress, and the error term will accordingly increase, which will in turn decrease the power to detect the effect of Coffee on Health somewhat, but will not affect the coefficient estimates by much. However, if we have increased measurement error in Coffee Consumption, then the proportion of variability explained by Coffee will decrease AND the error term will increase. We lose power on two fronts!
 +
 +
Here is a short r-script that demonstrates this idea: [[file: Gray_Q2MeasError.r]]
==== 5.====
==== 5.====
Line 200: Line 232:
;Discussion:
;Discussion:
-
 
+
No. The way to do this is starting with 3 variables in the model, and dropping the least "significant", one at a time, until you are left with only "significant" variables. We can perform a stepwise selection, but drop variables which become no longer "significant" after introduction of new variables.
 +
==== 8.====
==== 8.====
Line 206: Line 239:
;Discussion:
;Discussion:
-
 
+
No. After dropping the predictor, model changes. If we drop a predictor whose effect is not significant, the p-values of other predictors will change. We can see this from [http://www.utdallas.edu/~wiorkow%20/documents/Mod1Lect4Regnew.doc this example @ page 26-28]
==== 11.====
==== 11.====
Line 212: Line 245:
;Discussion:  
;Discussion:  
-
 
+
No. Size of tumors does provide some info about two treatments, one is the best and another is the worse. But it is not a good idea to estimate the difference between the two treatments by using the difference of size of tumors. It is so biased, because there are other factors which will effect the outcome, such as time in the disease. For example, our target is New York when we drive out of Toronto. But some day, we find everyone around is speaking Spanish. But the answer may be yes too, as Barack Obama's slogan showed: "Yes we can".   
==== 14.====
==== 14.====
Line 218: Line 251:
;Discussion:
;Discussion:
 +
 +
False. An interaction exists if the effect of one independent on the dependent variable varies over another independent variable. This tells us nothing about the relationship between the IVs.
 +
An interaction between two variables can occur whether or not the variables are correlated with one another.
 +
 +
{| class="wikitable"
 +
|-
 +
!
 +
! No Interaction
 +
! Interaction
 +
|-
 +
| '''No Correlation'''
 +
| [[File:Gray_Q14_nCnI.gif]] [[File:X1X2_Uncorr_NoInt.png|200px]]
 +
| [[File:Gray_Q14_nCI.gif]] [[File:X1X2_Uncorr_Int.png|200px]]
 +
|-
 +
| '''Correlation'''
 +
| [[File:Gray_Q14_CnI.gif]] [[File:X1X2_Corr_NoInt.png|200px]]
 +
| [[File:Gray_Q14_CI.gif]] [[File:X1X2_Corr_Int.png|200px]]
 +
|}
 +
 +
[[File: Gray_Q14.R‎]]
 +
 +
Here is an additional example using binary variables:
 +
[http://cnx.org/content/m31440/latest/ Illustration of the difference between correlation and interaction amongst independent variables]
 +
 +
== Assignment 3==
 +
 +
1) As we saw, 'Sector' appears to be an important predictor. Consider models using ses and Sector. Aim to estimate the between Sector
 +
gap as a function of ses if there is an interaction between Sector and ses. Check for and provide for a possible contextual effect of
 +
ses. Plot expected math achievement in each sector. Plot the gap with SEs. Consider the possibility that the apparently flatter effect
 +
of ses in Catholic school could be due to a non-linear effect of ses. How would you test whether this is a reasonable alternative explanation?
 +
 +
    myfit1<-lme(mathach~Sector*ses+cvar(ses,id),dd,random=~1+ses|id)
 +
    summary(myfit1)
 +
 +
 +
The interaction between ses and sector is significant (p<0.0001).
 +
To fully appreciate the nature of the relationship consider the following plot:
 +
 +
[[File:MathAchPerSector_Gray.png|200px]]
 +
 +
# Estimating the compositional (= between sector) effect of ses
 +
#
 +
 +
      wald( myfit1 )
 +
 +
      L <- list( 'Effect of ses' = rbind(
 +
          "Within-school" =  c( 0,1,0,0,0),
 +
          "Contextual"    =  c( 0,0,0,1,0),
 +
          "Compositional" =  c( 0,1,0,1,0)))
 +
 +
      L
 +
 +
      wald ( myfit1 , L
 +
 +
              numDF denDF  F.value p.value
 +
Effect of ses    2    77 27.43212 <.00001
 +
             
 +
                Estimate Std.Error DF  t-value p-value Lower 0.95 Upper 0.95
 +
  Within-school -1.778535  0.463645 77 -3.835987 0.00025  -2.701769  -0.855300
 +
  Contextual    3.090680  0.589674 77  5.241334 <.00001  1.916488  4.264872
 +
  Compositional  1.312145  0.832357 77  1.576421 0.11903  -0.345290  2.969581
 +
 +
 +
  # L matrix for the gap at a value of ses  :
 +
      #
 +
      # 2) Lmatrix for Public:
 +
      #    c( 1, ses, 1, 0, ses )
 +
      #
 +
      # 3) Lmatrix for Catholic:
 +
      #    c( 1, ses, 0, 0, 0)
 +
      #
 +
      # 4) Public - Catholic:
 +
      #    c( 0, 0, 1, 0 , ses)
 +
      #
 +
     
 +
      pred.gap <- expand.grid( ses = seq( -2, 2, .05))  # why so many?
 +
 +
      L.gap <- cbind( 0, 0, 1, 0, pred.gap$ses)
 +
      L.gap
 +
      wald( myfit1, L.gap )
 +
     
 +
      pred.gap <- cbind( pred.gap, as.data.frame( wald( myfit1, L.gap), se = 2))
 +
      some( pred.gap )
 +
 +
      td ( lty = c(1,2,2), lwd = 2, col = 'black')
 +
      xyplot( coef + L2 + U2 ~ ses, pred.gap,
 +
              type = 'l',
 +
              xlim = c(-2,2),
 +
              ylab = "Estimated Catholic - Public gap in MathAch (+/- 2 SEs)")
 +
             
 +
[[File:MathachGap_Gray.png]]
 +
 +
 +
 +
2) Take the example further by incorporating Sex. Consider the the 'contextual effect' of Sex which is school sex composition. Note that
 +
there are three types of schools: Girls, Boys and Coed schools. If you consider an interaction between Sector and school gender composition,
 +
you will see that the Public Sector only has Coed schools. What is the consequence of this fact for modeling sex composition and Sector effects.
 +
 +
Since I had no idea how to handle issue of the lack of non-coed schools in the Public board I maturely decided to ignore the problem and delete non-coed schools from the data set.  This analysis, treating proportion of males as a continuous variable, focuses entirely on Coed schools.
 +
 +
      dd$sex.p <- with( dd, cvar( Sex, id )) # Proportion of males
 +
      dd$ses.m <- with( dd, cvar( ses, id ))
 +
      dd$sex.cat <- factor( ifelse( dd$sex.p==1, "Girls", ifelse( dd$sex.p==0, "Boys", "Coed")))
 +
ddcd <- dd[(dd$sex.cat=="Coed"),]
 +
 +
With the exception of ses*Sector interactions were not significant.
 +
Because it was of substantive interest for the research question, I decided to leave Sector:Sex in
 +
the model
 +
     
 +
      fit3 <- lme( mathach ~ ses + Sector + Sex + Sector:Sex + ses:Sector + ses.m + sex.p, dd,
 +
      random = ~ 1 | id ,control = list( maxIter =  200, msMaxIter = 200, niterEM = 100))
 +
      summary( fit3 )
 +
      wald(fit3)
 +
 +
numDF denDF F.value p.value
 +
    7    59    435 <.00001
 +
                     
 +
Coefficients          Estimate Std.Error  DF t-value p-value Lower 0.95 Upper 0.95
 +
  (Intercept)            12.752    0.565 3600  22.581 <.00001    11.645      13.86
 +
  ses                    1.495    0.223 3600  6.715 <.00001      1.058      1.93
 +
  SectorPublic          -1.777    0.510  76  -3.483 0.00083    -2.792      -0.76
 +
  SexMale                1.037    0.412 3600  2.516 0.01191      0.229      1.85
 +
  ses.m                  3.048    0.585  76  5.209 <.00001      1.883      4.21
 +
  sex.p                  0.945    0.950  76  0.995 0.32312    -0.947      2.84
 +
  SectorPublic:SexMale    0.163    0.500 3600  0.327 0.74389    -0.816      1.14
 +
  ses:SectorPublic        1.320    0.294 3600  4.488 0.00001      0.743      1.90
 +
 +
Clearly the relationship between ses and math achievement is consistent for schools with a low proportion of male students, equal and a high proportion of male students.
 +
However female students consistently do worse than make students, by fairly constant amount, for all levels of ses, both school sectors and regardless of proportion of males in the school.
 +
[[File:GenderSect_Gray.png]]
 +
 +
 +
3) Does it appear that boys are better off in a boy's school and girls in a girl's school or are they better off in coed schools? How would
 +
you qualify your findings so parents don't misinterpret them in making decisions for their children?
 +
 +
From the following graphs, we can say that the overall perfromance performance of all schools(girls,boys and co-ed) is equal. But there are more number of students in coed school who perform lower than the students in single sex school. Also, there are very few girls who perform good in girls school as compared to co-ed school. So, I think girls are better off in co-ed school. Also, from the graph we can see that boys perfrom good in boys school as there are more number of students whose performance is good. So, Boys are better off in both boys and co-ed school.
 +
 +
[[File:q22.png]]
 +
[[File:p2.png]]
 +
   
 +
I thought another possibility would be to model this with both Sex and and the type of school (sex.cat = Coed or NotCoed) as predictors of math achievement.  Since the Public sector had no single sex schools, and there it was seen previously that Sector had an effect in math achievement, it seems reasonable to to conduct this analysis including only Catholic schools.
 +
      dd <- hs1[hs1$Sector=="Catholic",]
 +
      dd$sex.cat <- factor( ifelse( dd$sex.p==0, "NotCoed", ifelse( dd$sex.p==1, "NotCoed", "Coed")))
 +
      fit <- lme( mathach ~ 1 + sex.cat + Sex + sex.cat:Sex , dd,
 +
      random = ~ 1 | id ,control = list( maxIter = 200, msMaxIter = 200, niterEM = 100))
 +
      summary( fit )
 +
 +
Adding a random term for Sex did not improve the model significantly, thus this was not included in the model (p.value = 0.406).  Because only the RE model was altered, it was possible to use the anova function to assess the difference in fit.
 +
      fit2 <- lme( mathach ~ 1 + sex.cat + Sex + sex.cat:Sex , dd,
 +
      random = ~ 1 + dvar(Sex,id) | id ,control = list( maxIter = 200, msMaxIter = 200, niterEM = 100))
 +
      summary( fit2 )
 +
      # Adding a random effect for Sex did not improve the model
 +
      anova(fit,fit2)
 +
 +
Wald tests for the coefficients included in the model showed that the effect of school category (Coed/Not Coed) was not significant, nor was it significant as an interaction with the gender of the student.
 +
      Coefficients            Estimate Std.Error  DF t-value p-value Lower 0.95 Upper 0.95
 +
        (Intercept)              13.427    0.718 1796  18.699 <.00001    12.019      14.84
 +
        sex.catNotCoed          -0.635    1.313  33  -0.484 0.63185    -3.307      2.04
 +
        SexMale                  1.144    0.396 1796  2.890 0.00389      0.368      1.92
 +
        sex.catNotCoed:SexMale    1.489    1.467  33  1.016 0.31722    -1.494      4.47
 +
 +
However, it's always nice to look at the graphs anyway!
 +
Ans: [[File:CoedNotInteractSex_Gray.png]]
 +
 +
 +
 +
4) Is a low ses child better off in a high ses school or are they better off in a school of a similar ses? How about a high ses child in a
 +
low ses school? How would you qualify your findings so parents don't misinterpret them in making decisions for their children?
 +
 +
Ans: I have divided the whole data into two groups like "high ses school", and "low ses school". From this graph,we see that, In high ses schools, students with high ses perform better than the students with low ses. In low ses schools, students performs equally irrespective of ses status.
 +
<pre>
 +
dd$hls<-cut(dd$ses.mean, breaks=2,labels=c("low","high"))
 +
xyplot(mathach~ses|hls,dd,auto.key=T)
 +
</pre>
 +
 +
 +
 +
[[File:p6.png]]
 +
 +
 +
 +
5) Is a minority status child better off in a school with a higher proportion of minority status children or are they better off in a school
 +
with a low proportion? How would you qualify your findings so parents don't misinterpret them in making decisions for their children?
 +
 +
Ans: [[File:Figure.png]]
 +
 +
This graph is revealing that students in school with lower proportion minority perform better than the students in schools with higher proportion of minority.
 +
So, I think, if parents want their kids to perform good then they should send their kids to school with lower proportion of minority.
 +
 +
In the following graph we include the contextual/compositional effect of variables, then its a different story. These contextual variables can work positive or negative against students perfromance. So, parents need to be very careful while taking their decisions.
 +
 +
[[File:figur3.png]]
 +
 +
 +
 +
== Client Meeting ==
 +
[[File:Gray_Slide01.jpg|150px]]
 +
[[File:Gray_Slide02.jpg|150px]]
 +
[[File:Gray_Slide03.jpg|150px]]
 +
[[File:Gray_Slide04.jpg|150px]]
 +
[[File:Gray_Slide05.jpg|150px]]
 +
[[File:Gray_Slide06.jpg|150px]]
 +
[[File:Gray_Slide07.jpg|150px]]
 +
[[File:Gray_Slide08.jpg|150px]]
 +
[[File:Gray_Slide09.jpg|150px]]
 +
[[File:Gray_Slide10.jpg|150px]]
 +
 +
[[http://en.wikipedia.org/wiki/File:Hippocampus.gif Hippocampus Graphic]]

Latest revision as of 17:28, 23 March 2011

Contents

Assignment 1

1. Simpson's Paradox

Example: My friend and I play a basketball game and each shoot 20 shots. Who is the better shooter?

H65.PNG

But, who is the better shooter if you control for the distance of the shot? Who would you rather have on your team?

H32.PNG This is question of Simpson's Paradox.

H45.PNG

We can see from this figure, the relationship changed from negative to positive when we took the distance to our consideration. Black line linked probability of we two made. Red line is linked our performance when far, but blue when close.

Simpson’s paradox arises from one simple mathematical truth. Given eight real numbers: a, b, c, d, A, B, C, D with the following properties:12.png, then it is not necessarily true that122.png. In fact, it may be true that:13.png.

This is an obvious math reality, yet it has significant ramifications in Bayesian analysis, medical research, science and engineering studies, and societal statistical analysis. It is of concern for any statistical activity involving the calculation and analysis of ratios of two measurements.

Exmaple 2 (Real Income tax example)

File:Simpson1.pdf

2. Graphics to visualize data

Gray: rgl and p3d (include the use of the 'groups' parameter to produce trajectories

Introduction

File:Grey rgl p3d 1.pdf File:Grey rgl p3d 2.pdf

rgl is a library of functions that offers 3D real-time visualization functionality to the R programming environment (Adler & Murdoch, 2010), providing OpenGL implemention for R.

p3d is a library of functions which employs functions from RGL to help visualize statistical models expressed as a function of 2 independent variables with the possible addition of a categorical variable (Monette, 2009).

Package rgl

With rgl we create a ‘device’ , which is simply a window, within which a ‘world’ is created where we can create 3 dimensional shapes and through which we can navigate.

Grey World.png

Functions within the rgl package can be divided into 6 categories: (1) Device management functions (open and close devices, control active device) (2) Scene management functions (option to remove certain or all objects from the scene) (3) Export functions (creating image files) (4) Shape functions - essential plotting tools primitives (points, lines, triangles, quads) as well as higher level functions (text, spheres, surfaces).

Grey-Shapes.png

(5) Environment functions - modify the viewpoint, background and bounding box, adding light sources (6) Appearance function rgl.material(…).

Grey AppearanceOptions.png

Using shapes and surfaces within an rgl device, statistical data can be represented in 3 dimensions. Some advanced examples are available as demos or provided on the rgl website.

Gray Rgl 3d histogram.png Grey rgl example imulated animal abundance.png

A few of the functions from rgl are useful for manipulating 3D models created using p3d, since p3d contains many functions that inherit from rgl but taylor them to statistical methods. Thus all but a few are unnecessary for our purposes unless you would like to contribute functionality to p3d!



Package p3d

In this section I will focus on example code you may use to familiarize yourself with the capabilities of this package. You will require the tuition.Rdata (source:) and USIndicesIndustrialProd.Rdata (source:) data sets. Note that a few of the commands employed in sample code are from rgl, but these will likely be superceded by p3d functions as the package matures.

In this section I will focus on example code you may use to familiarize yourself with the capabilities of this package. You will require the File:Gray p3d ex Tuition.txt and File:Gray p3d ex USIndicesIndustrialProd.txt data sets. Note that a few of the commands employed in sample code are from rgl, but these will likely be superceded by p3d functions as the package matures.

Initialization code:


library( lattice )
library( nlme )
library( car )
library( spida )
library( rgl )
library( p3d )
tuit = read.table('tuition.Rdata',header=TRUE)
head(tuit)
prod = read.table('USIndicesIndustrialProd.Rdata',header=TRUE)
head(prod)



For the tuition data we will begin by plotting the annual cost of tuition from a sample of American Universities against the rates of faculty compensation and proportion of students who graduate.

Using mouse keys you can change the field of view and zoom in and out. Plot3d creates the 3D plot as shown on the right.

We can remove elements from the device using the function Pop3d(). This function removes elements starting with the most recently added item. Multiple items can be removed addition an numeric argument, ie.Pop3d(4)
Gray rgl navigation.png Gray p3d ex1.png


Init3d(cex = .8)
Plot3d(tuition ~ fac_comp + graduat, col = c("blue"), data = tuit)



Next we will subdivide the data by category, in this case whether the school is private (red) or public (blue) (variable name public.private).
Gray p3d ex2.png


Init3d(cex = .8)
Plot3d( tuition ~ fac_comp + graduat|public.private, col = c("blue", "red"), data = tuit)



Next we will add regression planes for private(red) and public(blue) schools using the lm() function to determine the fit, and Fit3d() to insert the plane in the graph. Axes and labels are added using Axes3d() and title3d().
Gray p3d ex3.png


fitpub = lm(tuition ~ fac_comp + graduat,subset=(public.private==0),data = tuit)
Fit3d( fitpub, col = c("blue"))

fitpri = lm(tuition ~ fac_comp + graduat,subset=(public.private==1),data = tuit)
Fit3d( fitpri, col = c("red"))

Axes3d()
title3d(main='Tuition predicted by grad rates and faculty salary -private (red) and public(blue) institutions')



Data ellipses are useful for understanding our data.
Gray p3d ex4.png


Ell3d()



We can change the view point of our graph using function view3d(theta,phi,fov,zoom), which takes polar coordinates. Note that view3d(0,0,0) will rotate the image to to face the x-z plane (y into the screen) and view3d(270,0,0) will rotate the image to to face the y-z plane (x into the screen). Function snap() will capture a still image of the current view. Note that to use movie3d() you must have ImageMagick installed to automatically convert png's to gif, otherwise you must use external software.

Gray p3d ex5.png GrayMovie.gif


view3d(0,0,0)
snap()

spin(theta = 0, phi = 0)

spins(inc.theta = 1/4, inc.phi = 0, theta = NULL, phi = NULL)

movie3d( spin3d(axis=c(0,1,0), rpm=20), duration=2, dir='movie' )



Here is an additional example, using data on the US indices of industrial products, plotting Mining production (MIN) over months and years. Adding the argument ‘groups=YR’ to Plot3d connects the months in a given year to produce trajectories. Gray p3d ex6.png


open3d(windowRect=c(100,100,800,800),cex = .8)
prod = read.table('USIndicesIndustrialProd.Rdata',header=TRUE)
head(prod)
Plot3d(MIN ~ YR+MONTH,data=prod,groups=YR)
Axes3d()
title3d(main='Industrial Production Mining (1947-1993)')
view3d(215,0,45)



Assignment 2

Statistics in the News: "Spousal support a royal pain?" Journal Abstract

Overly supportive spouses are not necessarily doing their partners a favour.

They could be prolonging the recovery of their injured spouses.

Men with highly attentive spouses reported higher levels of pain and more disability but did well on physical functions tests.

Women with highly attentive spouses didn't report feeling more pain or being more disabled. However, they performed more poorly on physical function tests than did women with less attentive spouses

MEDIA: Gray_RoyalPain.pdf

1

Question
whether the article suggest a causal relationship between two variables? If so which? Are the data observational or experimental?
Discussion

Yes, the article did suggest a causal relationship. One variable is the spousal solicitousness (attentiveness & support). Another is the degree of reported pain and disability. A third is actual physical function. Patient gender was also taken into consideration.

According to the report, men with chronic pain report more perceived pain and disability when they receive higher levels of spousal attention, and it is implied this is controlling for actual physical ability. For women there was no difference in self-reports of pain and disability with level of spousal support, but women who received more attention from their husbands had poorer physical function than those who did not.

The data are observational, because there is no manipulation or randomization in collecting the data.


2

Question
Can you think of alternative explanations to causality? Confounding factors? Or explanations consistent with causality? Mediating factors?
Discussion

Andy: Yes, maybe high degree of pain causes solicitousness, instead of solicitousness causing towards more pain. I don't think there exits a confounding factor. If there is, I believe it is LOVE, because a man's LOVE wins a highly attentive spouse and doesn't work as a narcotic as a woman feels. Then he may ask for more LOVEs by reporting hurt. That is a sweet answer to any woman, but tooth-hurting felt by any healthy man.

Also, LOVE could be the mediating factor too. And with high solicitousness, man's LOVE starts to fall in. He may move his body, more likely, which may cause more hurt. And then his physical function may recover faster. But to a woman, she likes to finding pieces of LOVEs through solicitousness. Her heart is numbed with those LOVEs. And then she will report she is better as an affectionate payback.

3

Question
Have any confounding factors been accounted for in the analysis?
Discussion

Emotional (men) or Physical (women) troubles outside the primary cause of pain. Men who are emotionally unstable may attract and encourage attentiveness in their wives, and also report a disproportionately high level of disability relative to their level of function. Women who are physically weak prior to injury may attract husbands who are highly supportive, but also be more susceptible to injuries that result in chronic pain.

4

Question
Have any mediating factors been controlled for in a way that vitiates a causal interpretation of the relationship?
Discussion

This does not appear to be the case.

5

Question
What is your personal assessment of the evidence for causality in the study that is the subject of the article?
Discussion

There is a good case to be made for both forward and backward causality in this study. In addition it would be nice to be able to ontrol for emotional and physical stability prior to chronic injury. Are frequencies distributed as expected? Are the proportions of highly attentive spouses equal across groups? ASSESSMENT: Judgement withheld pending further evidence


Paradoxes and Fallacies

2.

Question
You are studying observational data on the relationship between Health and Coffee (measured in grams of caffeine consumed per day). Suppose you want to control for a possible confounding factor 'Stress'. In this kind of study it is more important to make sure that you measure coffee consumption accurately than it is to make sure that you measure 'stress' accurately.
Discussion

True. It is more important to accurately measure Coffee Consumption if this is the variable of primary interest in the study.

Consider this from the analysis of variance framework. When measurement error is introduced, the variability in the outcome accounted for by that factor is decreased, and the error sums of squares increases. If we decrease accuracy in measuring Stress, and the error term will accordingly increase, which will in turn decrease the power to detect the effect of Coffee on Health somewhat, but will not affect the coefficient estimates by much. However, if we have increased measurement error in Coffee Consumption, then the proportion of variability explained by Coffee will decrease AND the error term will increase. We lose power on two fronts!

Here is a short r-script that demonstrates this idea: File:Gray Q2MeasError.r

5.

Question
In a multiple regression of Y on three predictors, X1, X2 and X3, if the coefficients of both X2 and X3, are not significant, it is safe to drop these two variable and perform a regression on X1 alone.
Discussion

No. The way to do this is starting with 3 variables in the model, and dropping the least "significant", one at a time, until you are left with only "significant" variables. We can perform a stepwise selection, but drop variables which become no longer "significant" after introduction of new variables.


8.

Question
In a multiple regression, if you drop a predictor whose effect is not significant, the p-values of the other predictors should not change very much.
Discussion

No. After dropping the predictor, model changes. If we drop a predictor whose effect is not significant, the p-values of other predictors will change. We can see this from this example @ page 26-28

11.

Question
In a model to assess the effect of a number of treatments on some outcome, we can estimate the difference between the best treatment and the worse treatment by using the difference in the mean outcomes.
Discussion

No. Size of tumors does provide some info about two treatments, one is the best and another is the worse. But it is not a good idea to estimate the difference between the two treatments by using the difference of size of tumors. It is so biased, because there are other factors which will effect the outcome, such as time in the disease. For example, our target is New York when we drive out of Toronto. But some day, we find everyone around is speaking Spanish. But the answer may be yes too, as Barack Obama's slogan showed: "Yes we can".

14.

Question
If two variables have a strong interaction, this implies a strong correlation.
Discussion

False. An interaction exists if the effect of one independent on the dependent variable varies over another independent variable. This tells us nothing about the relationship between the IVs. An interaction between two variables can occur whether or not the variables are correlated with one another.

No Interaction Interaction
No Correlation Gray Q14 nCnI.gif X1X2 Uncorr NoInt.png Gray Q14 nCI.gif X1X2 Uncorr Int.png
Correlation Gray Q14 CnI.gif X1X2 Corr NoInt.png Gray Q14 CI.gif X1X2 Corr Int.png

File:Gray Q14.R

Here is an additional example using binary variables: Illustration of the difference between correlation and interaction amongst independent variables

Assignment 3

1) As we saw, 'Sector' appears to be an important predictor. Consider models using ses and Sector. Aim to estimate the between Sector gap as a function of ses if there is an interaction between Sector and ses. Check for and provide for a possible contextual effect of ses. Plot expected math achievement in each sector. Plot the gap with SEs. Consider the possibility that the apparently flatter effect of ses in Catholic school could be due to a non-linear effect of ses. How would you test whether this is a reasonable alternative explanation?

    myfit1<-lme(mathach~Sector*ses+cvar(ses,id),dd,random=~1+ses|id)
    summary(myfit1)


The interaction between ses and sector is significant (p<0.0001). To fully appreciate the nature of the relationship consider the following plot:

MathAchPerSector Gray.png

  1. Estimating the compositional (= between sector) effect of ses
     wald( myfit1 )
     L <- list( 'Effect of ses' = rbind(
          "Within-school" =  c( 0,1,0,0,0),
          "Contextual"    =  c( 0,0,0,1,0),
          "Compositional" =  c( 0,1,0,1,0)))
     L
     wald ( myfit1 , L 
             numDF denDF  F.value p.value

Effect of ses 2 77 27.43212 <.00001

                Estimate Std.Error DF   t-value p-value Lower 0.95 Upper 0.95
 Within-school -1.778535  0.463645 77 -3.835987 0.00025  -2.701769  -0.855300
 Contextual     3.090680  0.589674 77  5.241334 <.00001   1.916488   4.264872
 Compositional  1.312145  0.832357 77  1.576421 0.11903  -0.345290   2.969581


 # L matrix for the gap at a value of ses  :
     #
     # 2) Lmatrix for Public:
     #    c( 1, ses, 1, 0, ses )
     #
     # 3) Lmatrix for Catholic:
     #    c( 1, ses, 0, 0, 0)
     #
     # 4) Public - Catholic:
     #    c( 0, 0, 1, 0 , ses)
     #
     
     pred.gap <- expand.grid( ses = seq( -2, 2, .05))   # why so many?
     L.gap <- cbind( 0, 0, 1, 0, pred.gap$ses)
     L.gap
     wald( myfit1, L.gap )
     
     pred.gap <- cbind( pred.gap, as.data.frame( wald( myfit1, L.gap), se = 2))
     some( pred.gap )
     td ( lty = c(1,2,2), lwd = 2, col = 'black')
     xyplot( coef + L2 + U2 ~ ses, pred.gap,
             type = 'l',
             xlim = c(-2,2),
             ylab = "Estimated Catholic - Public gap in MathAch (+/- 2 SEs)")
             

MathachGap Gray.png


2) Take the example further by incorporating Sex. Consider the the 'contextual effect' of Sex which is school sex composition. Note that there are three types of schools: Girls, Boys and Coed schools. If you consider an interaction between Sector and school gender composition, you will see that the Public Sector only has Coed schools. What is the consequence of this fact for modeling sex composition and Sector effects.

Since I had no idea how to handle issue of the lack of non-coed schools in the Public board I maturely decided to ignore the problem and delete non-coed schools from the data set. This analysis, treating proportion of males as a continuous variable, focuses entirely on Coed schools.

     dd$sex.p <- with( dd, cvar( Sex, id )) # Proportion of males
     dd$ses.m <- with( dd, cvar( ses, id ))
     dd$sex.cat <- factor( ifelse( dd$sex.p==1, "Girls", ifelse( dd$sex.p==0, "Boys", "Coed")))

ddcd <- dd[(dd$sex.cat=="Coed"),]

With the exception of ses*Sector interactions were not significant. Because it was of substantive interest for the research question, I decided to leave Sector:Sex in the model

     fit3 <- lme( mathach ~ ses + Sector + Sex + Sector:Sex + ses:Sector + ses.m + sex.p, dd,
     random = ~ 1 | id ,control = list( maxIter =  200, msMaxIter = 200, niterEM = 100))
     summary( fit3 )
     wald(fit3)

numDF denDF F.value p.value

    7    59     435 <.00001
                     

Coefficients Estimate Std.Error DF t-value p-value Lower 0.95 Upper 0.95

 (Intercept)            12.752     0.565 3600  22.581 <.00001     11.645      13.86
 ses                     1.495     0.223 3600   6.715 <.00001      1.058       1.93
 SectorPublic           -1.777     0.510   76  -3.483 0.00083     -2.792      -0.76
 SexMale                 1.037     0.412 3600   2.516 0.01191      0.229       1.85
 ses.m                   3.048     0.585   76   5.209 <.00001      1.883       4.21
 sex.p                   0.945     0.950   76   0.995 0.32312     -0.947       2.84
 SectorPublic:SexMale    0.163     0.500 3600   0.327 0.74389     -0.816       1.14
 ses:SectorPublic        1.320     0.294 3600   4.488 0.00001      0.743       1.90

Clearly the relationship between ses and math achievement is consistent for schools with a low proportion of male students, equal and a high proportion of male students. However female students consistently do worse than make students, by fairly constant amount, for all levels of ses, both school sectors and regardless of proportion of males in the school. GenderSect Gray.png


3) Does it appear that boys are better off in a boy's school and girls in a girl's school or are they better off in coed schools? How would you qualify your findings so parents don't misinterpret them in making decisions for their children?

From the following graphs, we can say that the overall perfromance performance of all schools(girls,boys and co-ed) is equal. But there are more number of students in coed school who perform lower than the students in single sex school. Also, there are very few girls who perform good in girls school as compared to co-ed school. So, I think girls are better off in co-ed school. Also, from the graph we can see that boys perfrom good in boys school as there are more number of students whose performance is good. So, Boys are better off in both boys and co-ed school.

Q22.png P2.png

I thought another possibility would be to model this with both Sex and and the type of school (sex.cat = Coed or NotCoed) as predictors of math achievement. Since the Public sector had no single sex schools, and there it was seen previously that Sector had an effect in math achievement, it seems reasonable to to conduct this analysis including only Catholic schools.

     dd <- hs1[hs1$Sector=="Catholic",]
     dd$sex.cat <- factor( ifelse( dd$sex.p==0, "NotCoed", ifelse( dd$sex.p==1, "NotCoed", "Coed")))
     fit <- lme( mathach ~ 1 + sex.cat + Sex + sex.cat:Sex , dd,
     random = ~ 1 | id ,control = list( maxIter = 200, msMaxIter = 200, niterEM = 100))
     summary( fit )

Adding a random term for Sex did not improve the model significantly, thus this was not included in the model (p.value = 0.406). Because only the RE model was altered, it was possible to use the anova function to assess the difference in fit.

     fit2 <- lme( mathach ~ 1 + sex.cat + Sex + sex.cat:Sex , dd,
     random = ~ 1 + dvar(Sex,id) | id ,control = list( maxIter = 200, msMaxIter = 200, niterEM = 100))
     summary( fit2 )
     # Adding a random effect for Sex did not improve the model
     anova(fit,fit2)

Wald tests for the coefficients included in the model showed that the effect of school category (Coed/Not Coed) was not significant, nor was it significant as an interaction with the gender of the student.

     Coefficients             Estimate Std.Error   DF t-value p-value Lower 0.95 Upper 0.95
       (Intercept)              13.427     0.718 1796  18.699 <.00001     12.019      14.84
       sex.catNotCoed           -0.635     1.313   33  -0.484 0.63185     -3.307       2.04
       SexMale                   1.144     0.396 1796   2.890 0.00389      0.368       1.92
       sex.catNotCoed:SexMale    1.489     1.467   33   1.016 0.31722     -1.494       4.47

However, it's always nice to look at the graphs anyway! Ans: CoedNotInteractSex Gray.png


4) Is a low ses child better off in a high ses school or are they better off in a school of a similar ses? How about a high ses child in a low ses school? How would you qualify your findings so parents don't misinterpret them in making decisions for their children?

Ans: I have divided the whole data into two groups like "high ses school", and "low ses school". From this graph,we see that, In high ses schools, students with high ses perform better than the students with low ses. In low ses schools, students performs equally irrespective of ses status.

dd$hls<-cut(dd$ses.mean, breaks=2,labels=c("low","high"))
xyplot(mathach~ses|hls,dd,auto.key=T)


P6.png


5) Is a minority status child better off in a school with a higher proportion of minority status children or are they better off in a school with a low proportion? How would you qualify your findings so parents don't misinterpret them in making decisions for their children?

Ans: Figure.png

This graph is revealing that students in school with lower proportion minority perform better than the students in schools with higher proportion of minority. So, I think, if parents want their kids to perform good then they should send their kids to school with lower proportion of minority.

In the following graph we include the contextual/compositional effect of variables, then its a different story. These contextual variables can work positive or negative against students perfromance. So, parents need to be very careful while taking their decisions.

Figur3.png


Client Meeting

Gray Slide01.jpg Gray Slide02.jpg Gray Slide03.jpg Gray Slide04.jpg Gray Slide05.jpg Gray Slide06.jpg Gray Slide07.jpg Gray Slide08.jpg Gray Slide09.jpg Gray Slide10.jpg

[Hippocampus Graphic]

Personal tools