--- title: "Testing and Modeling Multiple Dependent Variables" author: "Shane T. Mueller shanem@mtu.edu" date: "`r Sys.Date()`" output: rmdformats::readthedown: gallery: yes highlight: kate self_contained: no pdf_document: default html_document: df_print: paged word_document: reference_docx: ../template.docx always_allow_html: yes --- ```{r knitr_init, echo=FALSE, cache=FALSE} library(knitr) library(rmdformats) ## Global options options(max.print="75") opts_chunk$set(echo=TRUE, cache=TRUE, prompt=FALSE, tidy=TRUE, comment=NA, message=FALSE, warning=FALSE) opts_knit$set(width=75) ``` Suppose you measured two groups or conditions and have a lot of relatively weak measures of difference. You might find that each of the measures are correlated, and measure related constructs. Whether or not the individual measures show significant differences between groups, it might be nice to construct a composite of the DVs. But what is the right way to do that? There are some problems to think about. Different measures might be negatively correlated with one another, so averaging them would wipe out any effect. Or they may be of different magnitudes (e.g., completion time in seconds for one task, and accuracy for another). If you averaged these, one would swamp the other. Even if you had the same scale (two likert-scale responses), differences in variance could make averaging together problematic. Keeping them separate is also not always ideal. This produces multiple tests, and so you would have a greater chance of a false alarm. On the other hand, you may have several weak signals--each of which are noisy and none of which are significantly different, even if a composite score might be. There have been a number of procedures and tests developed to solve this problem. These include: * Hotellings T2: a generalization of the t-test for multiple DVs * The MANOVA Procedure: a generalization of ANOVA for multiple DVs * Canonical Correlation Analysis: correlating two sets of measures # Hotelling T2 The MANOVA is an extension of the ANOVA that attempts to run an ANOVA on a number of dependent measures, combining them optimally. We will start with an example data set in which three outcome variables are each weakly related to a group membership: ```{r} library(Hotelling) library(ggplot2) library(ICSNP) library(reshape2) set.seed(1000) n <- 350 group <- rep(1:2,each=n) xs <- rnorm(n*2, mean=group*.2, sd=1.4) ys <- rnorm(n*2, mean=4+ group*1.5, sd=15) zs <- rnorm(n*2, mean=3 - group*.2,sd=.9) ggplot(data.frame(group,xs,ys),aes(x=xs,y=ys,color=group)) + geom_point() + labs(title="X versus Y") ggplot(data.frame(group,xs,zs),aes(x=xs,y=zs,color=group)) + geom_point() + labs(title="X versus Z") long <- melt(data.frame(group,xs,ys,zs),id.vars=c("group")) long$group <- as.factor(long$group) ggplot(data=long,aes(x=(group),y=value)) + geom_violin(aes(fill=group),colour="grey20",scale="width") + facet_wrap(~variable) + theme_minimal() + scale_fill_manual(values=c("gold","cadetblue3")) ``` Notice that the three values we measured are on different scales, and they differ in different ways across groups. ```{r} t.test(xs~group) t.test(ys~group) t.test(zs~group) ``` None of these three measures differ significantly at a p<.05 level. Furthermore, the values are on different scales, and for some of them group 1 is higher, while for others group 1 is lower. If we had a high ICC, we might consider making a composite score-averaging these together, and trying to look at the measure that way. In this case, this would not be possible unless we either had some theory (expectations about positive/negative difference and scaling), or did some normalization to bring the measures all onto the same scale. So in an ideal world, maybe we would know something about the data and do this: ```{r} x2 <- xs/.2 y2 <- (ys-4)/1.5 z2 <- -(zs-3)/(.2) tmp <- data.frame(group=as.factor(rep(group,3)), val=c(x2,y2,z2), xyz=rep(c("X","Y","Z"), each=n)) ggplot(tmp,aes(x=group,y=val,col=group))+geom_violin(aes(fill=group),colour="grey20",scale="width") + geom_jitter(color="grey30",width=.05,height=0) +facet_wrap(~xyz) + theme_minimal() + scale_fill_manual(values=c("gold","cadetblue3")) composite <-rowMeans(cbind(x2,y2,z2)) t.test(tmp$val~as.factor(tmp$group)) ``` If we get lucky and have a good way of combining multiple values, we can still do a simple t-test. An alternative is the Hotelling $T^2$ test. This tests whether there is a difference between the groups on the three measures altogether. Hotelling's $T^2$ is available from several packages. But the way you call it differs across packages, so you need to be careful: ## Hotelling test from ICSNP ```{r} HotellingsT2(cbind(xs,ys,zs)~group) ``` ## hotelling.test from Hotelling package Previously, the Hotelling package had a function called hotel.test that worked differently from HotellingsT2. In recent versions this has been replaced by hotelling.test, that permits specifying the dependent measures either as a matrix or with $+$ syntax on the left of the ~ sign: ```{r} ##From Hotelling package print(hotelling.test(cbind(xs,ys,zs)~group)) ##This won't work in earlier versions of hotel.test. print(hotelling.test(xs+ys+zs~group)) ##correct; value is the same as ICSNP ``` Notice that the sign and scale of the components don't matter-- z is negatively related to the others, but if we reverse code it, the results are the same: ##Negatively code z ```{r} z2 <- 5-zs print(hotelling.test(xs+ys+z2~group)) print(HotellingsT2(cbind(xs,ys,z2)~group)) ``` Similarly, if we reduce scale of one of the components (y), everything stays the same: ```{r} y2 <- ys/10 print(hotelling.test(xs+y2+z2~group)) print(HotellingsT2(cbind(xs,y2,z2)~group)) ``` So, Hotelling's $T^2$ provides a way of creating sort of a composite score, without worrying about the scale or coding direction of the components. Notice that each individual component did not differ significantly across groups, but the set of three did. This also protects against multiple testing--if we'd measured 10 things and expected them all to differ a little but none did, we'd still have a high chance of a type-II false alarm error. Here, we do just one test. However, notice that the $T^2$ was not as strong as our "theory-based" composite score above, so we could do better if we have a principled method for combining values (and we were right). Adding garbage does not help! ```{r} xx <- rnorm(700) yy <- rnorm(700) print(hotelling.test(xs+y2+z2+ xx + yy~group)) ``` # MANOVA: Extending to Multiple Groups Just as we use one-way and multi-way ANOVA to generalize the t-test, we use the MANOVA ('multivariate analysis of variance') to generalize $T^2$. Sometimes people refer to the Wilks's Lambda as the alternative to MANOVA corresponding to the one-way ANOVA, but this is mostly nomenclature. R will sometimes do this automatically if given the right inputs. The simplest version is of course the two-group version, and we can see that the car library Anova will produce the same F test as Hotelling. The Manova() function is basically a specialized name for the same analysis. ```{r} library(car) lm(cbind(xs,ys,zs)~group) anova(lm(cbind(xs,ys,zs)~group)) manova(lm(cbind(xs,ys,zs)~group)) Anova(lm(cbind(xs,ys,zs)~group)) Manova(lm(cbind(xs,y2,z2)~group)) ``` Again, it doesn't matter the scale or direction of the individual DVs. what happens when we have three groups? We can actually give a multiple-column dependent measure to lm, but it does not really do what we might expect: ```{r} set.seed(1001) val <- rnorm(500) group <- as.factor(sample(c("A","B","C"),500,replace=T)) out1 <- 30 + val *.3 - as.numeric(group)*.25 + rnorm(500)*4 out2 <- 40 - val * .4 + as.numeric(group)*.3 + rnorm(500)*4 dat1 <- data.frame(val,group,out1,out2) dat2 <- data.frame(val,group,out=c(out1,out2),measure=rep(c("out1","out2"),each=500)) ggplot(dat2,aes(x=val,y=out,color=group))+geom_point()+facet_wrap(~measure) ##this just does things 'in parallel' lm1 <- lm(cbind(out1,out2)~val+group) summary(lm1) ``` Here, it really just runs a regression twice, once on each outcome variable. But if we give this lm to anova, it will do a MANOVA ```{r} library(car) anova(lm1) ``` However, this uses a "Type-I" MANOVA. Because we have multiple predictors, maybe we want a type-II MANOVA, which car::Anova and car::Manova do. ```{r} ##these two produce the same results: Anova(lm1) Manova(lm1) ``` # Interpreting the MANOVA Statistics When computing a standard ANOVA, we are dividing up our variance into pools accounted for by different predictors and combinations of predictors. In MANOVA, instead of variance, we have a covariance matrix that we are trying to do the same thing with. For $N$ outcomes, this involves $N$ variance terms, plus $N*(N-1)/2$ covariance (correlation) terms. The test statistics work by computing eigenvalues of this covariance matrix, and denote $\lambda_i$ as the $ith$ eigenvalue. Most test statistics are function of these $\lambda$ values, and there are a number of ways to combine these, and each has its own null-hypothesis distribution that is generally related to the F test. The following is from: https://en.wikiversity.org/wiki/Advanced_ANOVA/MANOVA > Choose from among these multivariate test statistics to assess whether there are statistically significant differences across the levels of the IV(s) for a linear combination of DVs. In general Wilks' $\lambda$ is recommended unless there are problems with small N, unequal ns, violations of assumptions, etc. in which case Pillai's trace is more robust: ## Roy's greatest characteristic root * Tests for differences on only the first discriminant function * Most appropriate when DVs are strongly interrelated on a single dimension * Highly sensitive to violation of assumptions - most powerful when all assumptions are met ## Wilks' lambda ($\Lambda$) * Most commonly used statistic for overall significance * Considers differences over all the characteristic roots * The smaller the value of Wilks' lambda, the larger the between-groups dispersion ## Hotelling's trace * Considers differences over all the characteristic roots ## Pillai's criterion * Considers differences over all the characteristic roots * More robust than Wilks'; should be used when sample size decreases, unequal cell sizes or homogeneity of covariances is violated Typically, packages will report Pillai's criterion or Pillai's trace. It is the sum of $(\lambda)/(1-\lambda)$, which should remind you of the effect size $f^2$ used in calculating power, since the eigenvalue is a measure of the proportion of variance. Hotelling's Trace (or Hotelling-Lawley's Trace) is the sum of the eigenvalues; Wilks $\lambda$ is the sum of $1/(1+\lambda_i)$. Roy's greatest root is the largest $\lambda$; essentially considering just the first principle component. Each of these tests are available for specifying in Anova, but "Pillai" is the default: ```{r} Manova(lm1,test.statistic="Wilks") Manova(lm1,test.statistic= "Hotelling-Lawley") Manova(lm1,test.statistic="Roy") ``` The different statistics give different interpretations. Roy's greatest root essentially asks whether there is a difference on the primary dimension of shared variance of the dependent variables. The others consider all the dimensions of shared variance, but combine these differently. Ultimately, the MANOVA often hides more than it reveals. Many statisticians have recommended you avoid using it unless you really need to, but it can come in handy, and understanding is important for evaluating other research. ## Conceptual relationship to PCA Conceptually, MANOVA is sort of like doing something like the following, which performs a regression on dimensions of a principal components analysis. If you are trying to do something like this, it would usually be better to use the MANOVA directly rather than trying to figure out something ad hoc like predicting eigen vectors 'by hand': ```{r} E <- eigen(cor((dat1[,3:4]))) print(E) p1 <-as.matrix(dat1[,3:4]) %*% as.matrix(E$vectors[,1]) p2 <- as.matrix(dat1[,3:4]) %*% as.matrix(E$vectors[,2]) m1 <- (lm(p1~val+group)) summary(m1) Anova(m1) m2 <- lm(p2~val+group) summary(m2) Anova(m2) ``` Notice that for two groups, the eigenvectors are essentially the mean and the difference between the observations. As the number of outcomes increases, these would be less constrained. If you look at the F tests for each predictor, you will see that the values are very similar to those produced in the PCA version (either on average, or max values, etc.). But this means that, depending on the test statistic, a MANOVA might also be considering strange and non-intuitive combinations of variables. Importantly, the group of dependent measures do not need to be correlated. Consider the following dependent variables. Here, out1 and out2 are independent, but group is related to the difference between them. Group is thus also indirectly related to each one, because the difference is larger when one is large or when the other is small (or both). Group2 and out3 are unrelated to the others. Some statisticians have explored procedures like this for doing ANOVA on PCA (e.g., https://iopscience.iop.org/article/10.1088/1742-6596/1899/1/012103/pdf). According to Abapihi et al. (2021), practitioners sometimes have found the MANOVA difficult to apply because of its strict assumptions, and propose ANOVA on the first principal component as an alternative. It seems like this would be successful if your first dimension is highly interpretable, but I wouldn't recommend it unless you take the PCA seriously first. For example, if your first component is highly interpretable and accounts for a substantial amount of variance, this might be easily justified, but it is mostly a similar procedure as Roy's GCR statistic. Other MANOVA statistics will incorporate all dimensions. ```{r} set.seed(150) yout1 <- rnorm(150) yout2 <- rnorm(150) yout3 <- rnorm(150) delta <- ((yout1-mean(yout1)) - (yout2- mean(yout2))) + rnorm(150)*5 group1 <- floor(rank(delta)/50) + 1 group2 <- sample(1:5,replace=T,size=150) out <- cbind(yout1,yout2,yout3) summary(lm(out~group1)) Manova(lm(out~group1+ group2),test.statistic="Roy") Manova(lm(out~group1+group2),test.statistic="Pillai") Manova(lm(out~group1+group2),test.statistic="Wilks") ``` ## Relation to Repeated Measures ANOVA This all seems like it is a bit like a repeated-measures ANOVA. By putting the data in 'long' format, we can just combine out1 and out2 into a single DV, then predict the mean difference between the two with a categorical value: ```{r} dat2 <- data.frame(val,group,out=c(out1,out2), measure=rep(c("out1","out2"), 500)) model.rm <- lm(out~val+group+measure,data=dat2) summary(model.rm) ``` This might be OK is some situations. But this is assuming that the two measures differ just by a constant. What if they have different scales, different variances, different directional relationships? Just like the t-test above, if we had a theory that could be used to combine these, it might be a better approach, but in this case, we are restricted in the inferences we can make. Notice that for each sub-model, the effects are in different directions, and so cancel out one another if we do it this way. We could sort of do this by predicting all the interactions too, but this begins to get very complicated such that a MANOVA might be preferred. ## Relationship to Logistic Regression, PCA, LDA, and Classification As we can see, although MANOVA seems like it is just a simple extension of ANOVA, it relates to many multi-variate concepts. For Hotelling's $T^2$ version, we are attempting to find whether there is a difference between two groups on multiple measures. We could easily turn this around; predicting group membership based on those multiple `predictors'. This is what methods such as logistic regression and linear discriminant analysis do. As we extend to multiple categories in MANOVA, this becomes similar to what some machine classification schemes permit--classifying categories based on multiple observed 'features'. Finally, we can understand MANOVA as sort of doing regressions on each principle component, and determining a reasonable means of combining those regressions at the end of the day. ### Exercise: The bfi data set in psych has data from a big-five inventory, and includes gender and age. Look at conscientiousness as a subscale, and examine whether it appears to be a coherent factor. Then, use MANOVA to predict the set of conscientiousness questions using gender and age. Does the personality depend on these? Recode age to a categorical 2- or 3-group factor, and test the interaction between gender and age. ```{r} library(psych) library(car) data(bfi) dplyr::select(bfi,A1:O5) lm1 <- lm(as.matrix(dplyr::select(bfi,A1:O5))~bfi$gender) Manova(lm1) ``` # Canonical Correlation Analysis MANOVA extends ANOVA/regression and allows multiple predictors and multiple outcome variables. A lesser-known alternative is Canonical Correlation Analysis (CCA), which tries to establish the cross-correlation between two sets of variables, and does so by establishing a dimensionality of the relationship. This is akin to a PCA, but rather than just finding the dimension of variability that is greatest, it finds the dimension of the covariance between the two variables that is the greatest. So, each set of measures A and B have a mapping onto latent variables (like PCA), which we call X and Y. This mapping is done so that the first dimension of X and the first dimension of Y are as highly correlated as we can get. Then, we find another two orthogonal dimensions, which compose the second set of canonical correlations. This can go on until we have N canonical correlations, where N is the smaller of the two numbers of variables. ## Packages and resources * https://stats.idre.ucla.edu/r/dae/canonical-correlation-analysis/ * ```cancor``` function in stats package * CCA package * candisc package ```{r} library(CCA) matcor(out,cbind(group1,group2)) img.matcor(matcor(out,cbind(group1,group2))) img.matcor(matcor(out,cbind(group1,group2)),type=2) x <- cc(out, cbind(group1,group2)) print(x) plot(x$scores$xscores,x$scores$yscores) ``` Here, we see the canonical correlation uses two dimensions, because group only has two variables. The first dimension finds a correlation between groups of .24, and the second .09. The first dimension correlates negatively with out1, positively with out2, and not with out3. The second dimension correlates with out3 only. On the other side, group 1 and group 2 correlate (negatively) with dimension 1, and group1 is positively related to dimension 2 but group2 is negatively related to dimension 2. We can sort of look at what is going on by plotting the first dimension xscores and yscores for each person---this is how each person maps into each of the first canonical correlation dimensions. We can see the correlation is .24, which is a small but probably significant relationship. ```{r} cor(x$scores$xscores[,1],x$scores$yscores[,1]) plot(x$scores$xscores[,1],x$scores$yscores[,1]) ``` ### Exercise Using the psych::BFI data set, use canonical correlation to determine a relationship between agreeableness and conscientiousness. Plot each individual's scores on the first pair of canonical correlation dimensions against one another.