#+TITLE: Twin analysis
#+AUTHOR: Klaus Holst & Thomas Scheike
#+STARTUP: showall
#+OPTIONS: ^:{}
#+OPTIONS: title:t author:t toc:nil
#+PROPERTY: header-args :exports both :results output :eval always
#+PROPERTY: header-args:R :session *R*
#+PROPERTY: header-args:R+ :colnames yes :rownames no :hlines yes  :width 550 :height 450

#+BEGIN_EXPORT yaml
output:
  rmarkdown::html_vignette:
    fig_caption: yes
#+END_EXPORT


This document provides a brief tutorial to analyzing twin data using
the *=mets=* package:
#+BEGIN_SRC R :exports code :ravel include=FALSE,echo=FALSE,message=FALSE,warning=FALSE
options(warn=-1, family="Times")
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/",
  out.width = "70%")
library("mets")
#+END_SRC

\(
\newcommand{\cov}{\mathbb{C}\text{ov}}
\newcommand{\cor}{\mathbb{C}\text{or}}
\newcommand{\var}{\mathbb{V}\text{ar}}
\newcommand{\E}{\mathbb{E}}
\newcommand{\unitfrac}[2]{#1/#2}
\newcommand{\n}{}
\)

The development version may be installed from /github/:
#+NAME: install
#+BEGIN_SRC R :exports code :ravel eval=FALSE
# install.packages("remotes")
remotes::install_github("kkholst/mets", dependencies="Suggests")
#+END_SRC

* Twin analysis, continuous traits

  In the following we examine the heritability of Body Mass
Index\n{}cite:korkeila_bmi_1991 cite:hjelmborg_bmi_2008, based on data
on self-reported BMI-values from a random sample of 11,411 same-sex
twins. First, we will load data

#+NAME: twinbmi
#+BEGIN_SRC R
data("twinbmi")
head(twinbmi)
#+END_SRC

The data is on /long/ format with one subject per row.
+ =tvparnr= :: twin id
+ =bmi= :: Body Mass Index (\(\mathrm{kg}/{\mathrm{m}^2}\))
+ =age= :: Age (years)
+ =gender= :: Gender factor (male,female)
+ =zyg= :: zygosity (MZ, DZ)

We transpose the data allowing us to do pairwise analyses
#+NAME: twinwide
#+BEGIN_SRC R
twinwide <- fast.reshape(twinbmi, id="tvparnr",varying=c("bmi"))
head(twinwide)
#+END_SRC

Next we plot the association within each zygosity group

#+NAME: scatterdens
#+BEGIN_SRC R :exports code :ravel echo=TRUE,message=FALSE,warning=FALSE
  library("cowplot")

  scatterdens <- function(x) {
      require(ggplot2)
      sp <- ggplot(x,
                  aes_string(colnames(x)[1], colnames(x)[2])) +
          theme_minimal() +
          geom_point(alpha=0.3) + geom_density_2d()
      xdens <- ggplot(x, aes_string(colnames(x)[1],fill=1)) +
          theme_minimal() +
          geom_density(alpha=.5)+
          theme(axis.text.x = element_blank(),
		legend.position = "none") + labs(x=NULL)
      ydens <- ggplot(x, aes_string(colnames(x)[2],fill=1)) +
          theme_minimal() +
          geom_density(alpha=.5) +
          theme(axis.text.y = element_blank(),
		axis.text.x = element_text(angle=90, vjust=0),
		legend.position = "none") +
          labs(x=NULL) +
          coord_flip()
      g <- plot_grid(xdens,NULL,sp,ydens,
                    ncol=2,nrow=2,
                    rel_widths=c(4,1.4),rel_heights=c(1.4,4))
      return(g)
  }
#+END_SRC


We here show the log-transformed data which is slightly more symmetric
and more appropiate for the twin analysis (see Figure \@ref(fig:scatter1) and ref:fig:scatter2)

#+NAME: scatter1
#+BEGIN_SRC R :exports both :ravel fig.cap="Scatter plot of logarithmic BMI measurements in MZ twins"
  mz <- log(subset(twinwide, zyg=="MZ")[,c("bmi1","bmi2")])
  scatterdens(mz)
#+END_SRC

#+NAME: scatter2
#+BEGIN_SRC R :exports both :results output graphics :file scatter2.jpg :ravel fig=TRUE,include=FALSE
  dz <- log(subset(twinwide, zyg=="DZ")[,c("bmi1","bmi2")])
  scatterdens(dz)
#+END_SRC

#+BEGIN_marginfigure
#+ATTR_LATEX: :width \textwidth :float nil :center t
#+RESULTS: scatter2
[[file:scatter2.jpg]]

#+LATEX: \captionof{figure}{Scatter plot of logarithmic BMI measurements in DZ twins.}
label:fig:scatter2
#+END_marginfigure

The plots and raw association measures shows considerable stronger
dependence in the MZ twins, thus indicating genetic influence of the
trait
#+BEGIN_SRC R
cor.test(mz[,1],mz[,2], method="spearman")
#+END_SRC

#+RESULTS:
:
: 	Spearman's rank correlation rho
:
: data:  mz[, 1] and mz[, 2]
: S = 165460000, p-value < 2.2e-16
: alternative hypothesis: true rho is not equal to 0
: sample estimates:
:       rho
: 0.6956209

#+BEGIN_SRC R
cor.test(dz[,1],dz[,2], method="spearman")
#+END_SRC

#+RESULTS:
:
: 	Spearman's rank correlation rho
:
: data:  dz[, 1] and dz[, 2]
: S = 2162500000, p-value < 2.2e-16
: alternative hypothesis: true rho is not equal to 0
: sample estimates:
:       rho
: 0.4012686

Ńext we examine the marginal distribution (GEE model with working
independence)

#+BEGIN_SRC R
  l0 <- lm(bmi ~ gender + I(age-40), data=twinbmi)
  estimate(l0, id=twinbmi$tvparnr)
#+END_SRC

#+RESULTS:
:             Estimate  Std.Err    2.5%   97.5%    P-value
: (Intercept)  23.3687 0.054534 23.2618 23.4756  0.000e+00
: gendermale    1.4077 0.073216  1.2642  1.5512  2.230e-82
: I(age - 40)   0.1177 0.004787  0.1083  0.1271 1.499e-133

#+BEGIN_SRC R :ravel echo=FALSE
  library("splines")
  l1 <- lm(bmi ~ gender*ns(age,3), data=twinbmi)
  marg1 <- estimate(l1, id=twinbmi$tvparnr)
#+END_SRC

#+RESULTS:


#+NAME: marg1
#+BEGIN_SRC R :exports both :results output graphics :file marg1.jpg :ravel include=FALSE,fig=TRUE
	  dm <- Expand(twinbmi,
		      bmi=0,
		      \gls{label}ender=c("male"),
		      age=seq(33,61,length.out=50))
	  df <- Expand(twinbmi,
		      bmi=0,
		      gender=c("female"),
		      age=seq(33,61,length.out=50))

	  plot(marg1, function(p) model.matrix(l1,data=dm)%*%p,
	       data=dm["age"], ylab="BMI", xlab="Age",
               ylim=c(22,26.5))
	  plot(marg1, function(p) model.matrix(l1,data=df)%*%p,
               data=df["age"], col="red", add=TRUE)
	  legend("bottomright", c("Male","Female"),
		 col=c("black","red"), lty=1, bty="n")
#+END_SRC


#+BEGIN_marginfigure
#+ATTR_LATEX: :width \textwidth :float nil :center t
#+RESULTS: marg1
[[file:marg1.jpg]]


#+LATEX: \captionof{figure}{...}
label:fig:marg1
#+END_marginfigure

** Polygenic model

   Decompose outcome into
   \begin{align*}
   Y_i = A_i + D_i + C + E_i, \quad i=1,2
    \end{align*}

- \(A\) :: Additive genetic effects of alleles
- \(D\) :: Dominante genetic effects of alleles
- \(C\) :: Shared environmental effects
- \(E\) :: Unique environmental genetic effects

Dissimilarity of MZ twins arises from unshared environmental effects
only! \(\cor(E_1,E_2)=0\) and
\begin{align*}
\cor(A_1^{MZ},A_2^{MZ}) = 1, \quad
\cor(D_1^{MZ},D_2^{MZ}) = 1,
\end{align*}
\begin{align*}
\cor(A_1^{DZ},A_2^{DZ}) = 0.5, \quad
\cor(D_1^{DZ},D_2^{DZ}) = 0.25,
\end{align*}

   \begin{align*}
   Y_i = A_i + C_i + D_i + E_i
   \end{align*}
   \begin{align*}
   A_i \sim\mathcal{N}(0,\sigma_A^2), C_i
   \sim\mathcal{N}(0,\sigma_C^2), D_i
   \sim\mathcal{N}(0,\sigma_D^2),
   E_i \sim\mathcal{N}(0,\sigma_E^2)
   \end{align*}

  \begin{gather*}
    \cov(Y_{1},Y_{2}) = \\
    \begin{pmatrix}
      \sigma_A^2 & 2\Phi\sigma_A^2 \\
      2\Phi\sigma_A^2 & \sigma_A^2
    \end{pmatrix} +
    \begin{pmatrix}
      \sigma_C^2 & \sigma_C^2 \\
      \sigma_C^2 & \sigma_C^2
  \end{pmatrix} +
    \begin{pmatrix}
      \sigma_D^2 & \Delta_{7}\sigma_D^2 \\
      \Delta_{7}\sigma_D^2 & \sigma_D^2
  \end{pmatrix} +
  \begin{pmatrix}
    \sigma_E^2 & 0 \\
    0 & \sigma_E^2
  \end{pmatrix}
\end{gather*}



#+BEGIN_SRC R :exports code
  dd <- na.omit(twinbmi)
  l0 <- twinlm(bmi ~ age+gender, data=dd,
              DZ="DZ", zyg="zyg", id="tvparnr", type="sat")

#+END_SRC

#+RESULTS:

#+BEGIN_SRC R
    l <- twinlm(bmi ~ ns(age,1)+gender, data=twinbmi,
               DZ="DZ", zyg="zyg", id="tvparnr", type="cor", missing=TRUE)
    summary(l)
#+END_SRC

#+RESULTS:
#+begin_example
____________________________________________________
Group 1
                        Estimate Std. Error   Z value Pr(>|z|)
Regressions:
   bmi.1~ns(age, 1).1    4.16937    0.16669  25.01334   <1e-12
   bmi.1~gendermale.1    1.41160    0.07284  19.37839   <1e-12
Intercepts:
   bmi.1                22.53618    0.07296 308.87100   <1e-12
Additional Parameters:
   log(var)              2.44580    0.01425 171.68256   <1e-12
   atanh(rhoMZ)          0.78217    0.02290  34.16186   <1e-12
____________________________________________________
Group 2
                        Estimate Std. Error   Z value Pr(>|z|)
Regressions:
   bmi.1~ns(age, 1).1    4.16937    0.16669  25.01334   <1e-12
   bmi.1~gendermale.1    1.41160    0.07284  19.37839   <1e-12
Intercepts:
   bmi.1                22.53618    0.07296 308.87100   <1e-12
Additional Parameters:
   log(var)              2.44580    0.01425 171.68256   <1e-12
   atanh(rhoDZ)          0.29924    0.01848  16.19580   <1e-12

                       Estimate 2.5%    97.5%
Correlation within MZ: 0.65395  0.62751 0.67889
Correlation within DZ: 0.29061  0.25712 0.32341

'log Lik.' -29020.12 (df=6)
AIC: 58052.24
BIC: 58093.29
#+end_example

A formal test of genetic effects can be obtained by comparing the MZ and DZ correlation:
#+BEGIN_SRC R
estimate(l,contr(5:6,6))
#+END_SRC

#+RESULTS:
:                           Estimate Std.Err   2.5%  97.5%   P-value
: [1@atanh(rhoMZ)] - [3....   0.4829 0.04176 0.4011 0.5648 6.325e-31
:
:  Null Hypothesis:
:   [1@atanh(rhoMZ)] - [3@atanh(rhoDZ)] = 0


#+BEGIN_SRC R
    l <- twinlm(bmi ~ ns(age,1)+gender, data=twinbmi,
               DZ="DZ", zyg="zyg", id="tvparnr", type="cor", missing=TRUE)
    summary(l)
#+END_SRC

#+RESULTS:
#+begin_example
____________________________________________________
Group 1
                        Estimate Std. Error   Z value Pr(>|z|)
Regressions:
   bmi.1~ns(age, 1).1    4.16937    0.16669  25.01334   <1e-12
   bmi.1~gendermale.1    1.41160    0.07284  19.37839   <1e-12
Intercepts:
   bmi.1                22.53618    0.07296 308.87100   <1e-12
Additional Parameters:
   log(var)              2.44580    0.01425 171.68256   <1e-12
   atanh(rhoMZ)          0.78217    0.02290  34.16186   <1e-12
____________________________________________________
Group 2
                        Estimate Std. Error   Z value Pr(>|z|)
Regressions:
   bmi.1~ns(age, 1).1    4.16937    0.16669  25.01334   <1e-12
   bmi.1~gendermale.1    1.41160    0.07284  19.37839   <1e-12
Intercepts:
   bmi.1                22.53618    0.07296 308.87100   <1e-12
Additional Parameters:
   log(var)              2.44580    0.01425 171.68256   <1e-12
   atanh(rhoDZ)          0.29924    0.01848  16.19580   <1e-12

                       Estimate 2.5%    97.5%
Correlation within MZ: 0.65395  0.62751 0.67889
Correlation within DZ: 0.29061  0.25712 0.32341

'log Lik.' -29020.12 (df=6)
AIC: 58052.24
BIC: 58093.29
#+end_example

* Twin analysis, censored outcomes

* Twin analysis,  binary traits


* Time to event


* backmatter                                                         :ignore:


 bibliography:mets.bib
 bibliographystyle:plain
