# jh 2026.10.24 james.hanley@mcgill.ca

Entities = c(rep("Families",5),
             "MLB-Players",
             "Pro. Golfers",
             "NHANES subjects",
             "Households")

RelatedUnits = c("Brother",rep("Twin/triplet",4),
                 "Season","Round","Day","Person")

Observation = c("Height",
                rep("Proportion of year with middle ear effusion",2),
                rep("Birth Weight",2), "Batting Average","Score","Activity Level","Age")



pdf(file= "NineDatasets.pdf",
    height=9, width=9)

par(mfrow = c(3, 3), 
    mar = c(5, 5, 3, 3),  # Shrinks space around individual plots
    oma = c(0, 0, 2, 0))  # Adds a small space at the very top for a main title

CEX=1.1

for( i.choice in 1:9) {
  
############ brothers

if( i.choice == 1 ) {
  
  DS = read.csv(
    paste0(
    "https://jhanley.biostat.mcgill.ca/galton/",
    "BrothersAndOtherDatasets/GaltonBrothers.csv") )
  names(DS)

  dim(DS)
  table(DS$n.brothers)
  
  # remove ones from families > 4, as per FG
  
  DS = DS[DS$n.brothers <= 4,]
  
  dataset = DS[,2:5]
  names(dataset)[c(1,3,4)]=
    c("entity","unit","measure")
  
  dim(dataset) ; 
  head(dataset); tail(dataset)

}

########### duration of ear infections in twins/triplets
  
if( i.choice == 2 ) { # Identical 
  
  DS <- read.table(
    "https://jhanley.biostat.mcgill.ca/c622/otitis-data-R.txt", 
    skip = 1, col.names = c("family", 
                            "proportion.1", 
                            "proportion.2",
                            "proportion.3", "z")) ; dim(DS) ; head(DS)
 
  DS = DS[DS$z==1,] # Identical
    
  DS <- reshape(data = DS, direction = "long",
          varying = c("proportion.1", "proportion.2", "proportion.3"),
          timevar = "sibling" )
  
  DS = DS[ order(c(DS$family, DS$sibling)), ]
  
  # if no 3rd infant
  DS <- subset(DS, !is.na(proportion)) ; rownames(DS) <- NULL
  
  n = sum( DS$proportion==0 ) # to move away from zero
  DS$proportion[DS$proportion==0] = runif(n,0.015,0.03) 
  DS$logit = log( DS$proportion/(1-DS$proportion) )
    
  n = as.numeric(table(DS$family))
  DS$member.no = as.numeric( unlist( lapply(n, function(x) 1:x) ) )
  
  dataset=DS # names(DS)
  names(dataset)[c(1,5,6)] = c("entity","unit","measure")
  
  dim(dataset) ; 
  head(dataset); tail(dataset)
}
  
######### non-ID
  
if( i.choice == 3 ) { # not Identical 
    
    DS <- read.table(
      "https://jhanley.biostat.mcgill.ca/c622/otitis-data-R.txt", 
      skip = 1, col.names = c("family", 
                              "proportion.1", 
                              "proportion.2",
                              "proportion.3", "z")) ; dim(DS) ; head(DS)
    
    DS = DS[DS$z > 1,] # Identical
    
    DS <- reshape(data = DS, direction = "long",
                  varying = c("proportion.1", "proportion.2", "proportion.3"),
                  timevar = "sibling" )
    
    DS = DS[ order(c(DS$family, DS$sibling)), ]
    
    DS <- subset(DS, !is.na(proportion)) ; rownames(DS) <- NULL
    
    n = sum( DS$proportion==0 ) # to move up from zero
    DS$proportion[DS$proportion==0] = runif(n,0.015,0.03) # away from zero
    DS$logit = log( DS$proportion/(1-DS$proportion) )
    
    n = as.numeric(table(DS$family))
    DS$member.no = as.numeric( unlist( lapply(n, function(x) 1:x) ) )
    
    dataset=DS # names(DS)
    names(dataset)[c(1,5,6)] = c("entity","unit","measure")
    
    dim(dataset) ; 
    head(dataset); tail(dataset)
}
  
########### "Birth weights of Twins born of HIV+ mothers",
  
  if( i.choice == 4 ) {
    
    DS = read.csv(
      paste0(
        "https://jhanley.biostat.mcgill.ca/galton/",
        "BrothersAndOtherDatasets/hivtwins_data.csv") )
    
    names(DS)
    

    U = unique( DS$BATCHID ) ; length(U)
    
    DS = DS[ !is.na(DS$IDENTICAL) & DS$IDENTICAL == 1,]
    dim(DS)
    
    U = unique( DS$BATCHID ) ; length(U)
    
    dataset = NULL
    
    for ( i in 1:length(U) ) { # i = 1
      d = DS[ DS$BATCHID == U[i] , ] # str(d)
      WEIGHTS = d[17:19]
      WEIGHTS = WEIGHTS[ !is.na(WEIGHTS) ]
      n = length(WEIGHTS)
      if(n>1) dataset=rbind(dataset,
                  data.frame(
                    entity = rep(i,n),
                    unit= 1:n,
                    measure =  WEIGHTS,
                    identical = d$IDENTICAL==1) )
    }
    
    dim(dataset)
    head(dataset)
    # summary(dataset)
    
  }
  
  
############ "Birth weights of Twins born of HIV+ mothers",
  
  if( i.choice == 5 ) {
    
    DS = read.csv(
      paste0(
        "https://jhanley.biostat.mcgill.ca/galton/",
        "BrothersAndOtherDatasets/hivtwins_data.csv") )
    
    names(DS)
    
    U = unique( DS$BATCHID ) ; length(U)
    
    DS = DS[ !is.na(DS$IDENTICAL) & DS$IDENTICAL == 0,]
    dim(DS)
    
    U = unique( DS$BATCHID ) ; length(U)
    
    dataset = NULL
    
    for ( i in 1:length(U) ) { # i = 1
      d = DS[ DS$BATCHID == U[i] , ] # str(d)
      WEIGHTS = d[17:19]
      WEIGHTS = WEIGHTS[ !is.na(WEIGHTS) ]
      n = length(WEIGHTS)
      if(n>1) dataset=rbind(dataset,
                            data.frame(
                              entity = rep(i,n),
                              unit= 1:n,
                              measure =  WEIGHTS,
                              identical = d$IDENTICAL==1) )
    }
    
    
    head(dataset)
    dim(dataset)
    summary(dataset)
    
}
  
########## YEARLY BATTING AVERAGES OF BASEBALL PLAYERS
  
  if( i.choice == 6 ) {
    
    # install.packages("Lahman") if not 
    
    if (!require("Lahman", quietly = TRUE)) {
      install.packages("Lahman")
    }

    library(Lahman)
    
    if (!require("lme4", quietly = TRUE)) {
      install.packages("lme4")
    }
    
    if (!require("performance", quietly = TRUE)) {
      install.packages("performance")
    }
    
    library(lme4)
    library(performance)
    
    # Pull the built-in data frames directly
    data("Batting")
    data("People")
    
    # Combine stats for players
    yearly_totals <- aggregate(cbind(AB, H) ~ 
              playerID + yearID, data = Batting, FUN = sum)
    
    FULL= 300
    # Define a "full season" (minimum 300 At-Bats)
    full_seasons <- subset(yearly_totals, AB >= FULL)
    head(full_seasons,5)
    names(full_seasons)
    
    # Count how many full seasons each player has
    season_counts <- table(full_seasons$playerID)
    vets = dimnames(season_counts)[[1]][season_counts >= 10]
    
    # Keep only the yearly stats belonging to these veteran players
    veterans <- full_seasons[
      full_seasons$playerID %in% vets,] 
    dim(veterans)
    ( n = length(unique(veterans$playerID)))
    
    veterans$BA <- round(1000*veterans$H / veterans$AB, 3)
    
    dataset = data.frame(
      entity   = veterans$playerID, # table(dataset$person)
      unit = veterans$yearID,
      measure  = veterans$BA)
    
    dataset = dataset[order(dataset$entity, dataset$unit),]
    head(dataset,30); 
    tail(dataset,30);
    dim(dataset)
    
  }
  
############ golf

if( i.choice == 7 ) {
  
  # from Kaggle (? sorry did not document source)
  
  DS = read.csv(
    paste0(
      "https://jhanley.biostat.mcgill.ca/galton/",
      "BrothersAndOtherDatasets/Full_Leaderboard_Table.csv") )
  dim(DS); names(DS)
  
    freq= sort(table(DS$PLAYER))
    tail(freq)
    names = dimnames(freq)[[1]]
    names = names[freq >= 25 ] # at least 25 tournaments
    length(names)
    
    dataset = NULL
    
    for(i in 1: length(names) ) { # i=1
        d = DS[ DS$PLAYER == names[i], ]
        n = dim(d)[1]
       id = d$tournamentID[round(n/2)] # middlemost
        d =  d[d$tournamentID == id,
             c("PLAYER","tournamentID","R1","R2")]
       if( !is.na(d$R1) & !is.na(d$R2) &
           d$R1 > 60 & d$R2 > 60 ) {
             dataset=rbind(dataset,
                   data.frame(
                    entity = rep(names[i],2),
                    tournament = rep(id,2),
                    unit = c(1,2),
                    measure= as.numeric(c(d$R1,d$R2)) 
                             )
                          )
        }
    }
    
    head(dataset); dim(dataset)
    
}


############ physical activity NHANES


if( i.choice == 8) {

   url <- paste0(
      "https://wwwn.cdc.gov/Nchs/Data/Nhanes/",
   "Public/2013/DataFiles/PAXDAY_H.XPT")

   tmp <- tempfile(fileext = ".XPT")
   on.exit(unlink(tmp), add = TRUE)

   download.file(url, tmp, mode = "wb", quiet = TRUE)

   ds <- haven::read_xpt(tmp)
   dim(ds)
   unlink(tmp)
   
   if (file.exists(tmp)) {
     # Remove the file
     file.remove(tem)
   }

   # table(ds$PAXQFD)

   ds <- ds[!is.na(ds$PAXQFD) &
           ds$PAXQFD == 0  , ]  # no problematic minutes

   dim(ds)[1]

   ds <- ds[!is.na(ds$PAXWWMD) & 
           ds$PAXWWMD >  480 , ]  # > 8 hrs
   dim(ds)[1]

   # summary(ds$PAXMTSD)
   # summary(ds$PAXWWMD)

   ds$mims_per_wake_minute <- ds$PAXMTSD / ds$PAXWWMD
   dim(ds)[1]
   #plot(ds$PAXWWMD, ds$PAXMTSD)

   summary(ds$mims_per_wake_minute)
   #hist(ds$mims_per_wake_minute,breaks=100)

   names(ds)
   
   U = unique(ds$SEQN)
   length(U)
   
   dataset = NULL
   
   logs = 0 # toggle between 0 (no) and 1 (yes)
   
   for(i in 1: length(U)   ) { # i=1
     d = ds[ ds$SEQN == U[i], ]
     n = dim(d)[1]
     if(n >= 2){

        dataset=rbind(dataset,
            data.frame(
            entity = rep(i,n),
            unit = 1:n,
            measure =  logs * log2( d$mims_per_wake_minute ) +
                   (1-logs) *       d$mims_per_wake_minute )
        )
     }
     
     
   }
   
   head(dataset,20)
   dim(dataset)
  
   
}
   

########### Ages of people in households of 2 or more persons 

# Census of Bere Island (1925)


if( i.choice == 9 ) {
  
  fname=paste0(
    "https://jhanley.biostat.mcgill.ca/galton/",
    "BrothersAndOtherDatasets//Bear1926-aug-corrected.csv") 

  DS = read.csv(fname)
  #names(DS)
  
  household.sizes = table(DS$aform_name)
  length(household.sizes)
  
  houses = household.sizes[household.sizes > 1]
  length(houses)
  
  Household.ids = dimnames(houses)[[1]]
  N = length(Household.ids)
  
  DS$name = paste0(DS$first_name,".",DS$surname)
  
  names(DS)
  selectedColumns = c(3,5,26,10,20) 
  
  dataset = DS[DS$aform_name %in% Household.ids, selectedColumns]
  dim(dataset)
  names(dataset)[c(1,3,4,5)] = c("entity","unit",
   "RelationToHead","measure") 
  dataset[75:94,]
  
  # table(dataset$RelationToHead) if want to restrict

}
  
####################################################
####### analysis ....  #############################
####################################################

library(lme4)
library(performance)
  
# hist(dataset$measure)

summary(dataset$measure)

model <- lmer(measure ~ 1 + (1 | entity), 
              data = dataset )

print( summary(model) )

# Extract variances into a clean data frame
vars <- as.data.frame(VarCorr(model))

#Pull the specific variance values
Between_var <- vars[vars$grp == "entity",   "vcov"]   
Within_var  <- vars[vars$grp == "Residual", "vcov"] 

cat("Random Effect Variance:", Between_var, "\n")
cat("Residual Variance:", Within_var, "\n")

icc = icc(model)
print( icc )

# make pairs

U = unique(dataset$entity)

Pairs = NULL # random pairs of occasions

for(i in 1: length(U) ) { 
  d = dataset[ dataset$entity == U[i], ] # str(d)
  measure = d$measure 
  measure = measure[!is.na(measure)]
  n = length(measure)
  if(n>1){
    order = sample(1:n,2)
    Pairs =rbind(Pairs,
                data.frame(
                  entity = d$entity[1],
                  x = measure[ order[1] ],
                  y = measure[ order[2] ] ))
  }
}


x = Pairs$x ; y = Pairs$y

fit = lm( y ~ x)

txt = paste0("Var-Between: ", 
    format(signif(Between_var, digits = 2), big.mark = ","),
          "; Var-Within: ", 
    format(signif(Within_var, digits = 2), big.mark = ",") )

axis_limits <- range(c(x,y))


plot(-99, -99,
     cex = 0.15, pch=19,
     xlim=axis_limits, 
     ylim=axis_limits,
     xlab=paste0("Known ",RelatedUnits[i.choice]),
     ylab=paste0("Unknown ",RelatedUnits[i.choice]),
     main = paste0(Observation[i.choice],"\n",txt),
     cex.main=CEX, cex.lab=CEX, cex.axis=CEX,
     frame=TRUE)

# Draw a box tightly around the plot area (standard border)
box(which = "figure", col = "black", lwd = 1.0)

abline(h = mean(y), lwd=0.25 )
abline(v = mean(x), lwd=0.25 )

# Draw  transparent data points first

COL = rgb(0.1, 0.1, 0.1, 0.15)
if( i.choice == 8) COL = rgb(0.02, 0.02, 0.02, 0.15)
points(x, y, pch = 16, col = COL)

x.lo =  axis_limits[1]
x.hi =  axis_limits[2]

y.lo = mean(Pairs$y) + fit$coefficients[2] *  ( x.lo - mean(Pairs$x)  )
y.hi = mean(Pairs$y) + fit$coefficients[2] *  ( x.hi - mean(Pairs$x)  )

segments(x.lo,y.lo, x.hi,y.hi, col = "red", lwd = 2)

y.lo = mean(Pairs$y) + 1 *  ( x.lo - mean(Pairs$x)  )
y.hi = mean(Pairs$y) + 1 *  ( x.hi - mean(Pairs$x)  )

segments(x.lo,y.lo, x.hi,y.hi,  lwd = 0.5)


n=dim(dataset)[1]
text(x.lo,x.hi,
     paste0(
       "ICC\n", sprintf("%.2f", 
          round(as.numeric(icc[1]),2) ),
       "\nn\n", n) ,
     adj=c(0,1.05), cex=CEX)

text(x.hi,
     x.lo,
     paste(length(U), Entities[i.choice]),
     adj=c(1,-0.1), cex=CEX)


if(i.choice == 2 | i.choice == 4 ) text(
  x.hi, mean(Pairs$y),
  "IDENTICAL",     adj=c(1,1.5), cex=0.8*CEX)

if(i.choice == 3 | i.choice == 5 ) text(
  x.hi, mean(Pairs$y),
  "NON-\nIDENTICAL", adj=c(1,1.2), cex=0.8*CEX)


if(i.choice == 2 | i.choice == 3 ) text(
  x.hi, 
  (1/3)*mean(Pairs$y) +(2/3)* min(dataset$measure) ,
  "logit scale",     adj=c(1,0.5), cex=0.8*CEX)
   
} # i.choice  

dev.off()