# Scale ID: 			MMSE
# Scale Name: 		Mini Mental State Examination
# TILDA Variables: 	COGmmse
# Dataset:      		TILDA Waves 1-6
# Author:
# Institution:  		The Irish Longitudinal Study on Ageing (TILDA)
# 
# Description:
# Generates scoring for the Mini Mental State Examination accounting for best score between Serial Sevens and WORLD.
# 
# Version:      1.0
# Date:         2026-09-01
# Language:     R
#
# Assumption: the working data frame is called `data`.

score_src <- c(
  "ph121","ph126","ph122","ph123","ph124","ph127","ph128","ph129","ph130",
  "ph131","ph132","ph133","ph134","ph135","ph136","ph137","ph138","ph139",
  "ph140","ph141"
)

for (v in score_src) {
  out <- paste0(v, "score")
  data[[out]] <- data[[v]]
  bad <- !is.na(data[[out]]) &
         (data[[out]] == -1 | (data[[out]] >= 97 & data[[out]] <= 99))
  data[[out]][bad] <- NA_real_
}

# Best score between ph133 and ph134; rowmax ignores one missing value.
a <- data$ph133score
b <- data$ph134score
data$ph1334score <- ifelse(
  is.na(a) & is.na(b),
  NA_real_,
  pmax(a, b, na.rm = TRUE)
)

mmse_items <- c(
  "ph121score","ph126score","ph122score","ph123score","ph124score",
  "ph127score","ph128score","ph129score","ph130score","ph131score",
  "ph132score","ph1334score","ph135score","ph136score","ph137score",
  "ph138score","ph139score","ph140score","ph141score"
)

# Stata egen rowtotal() ignores missing components and returns 0 if all are missing.
data$mmsetotal_2 <- rowSums(data[mmse_items], na.rm = TRUE)

data$mmsetotal_2[!is.na(data$hh005) & data$hh005 > 1] <- -1

# The Stata source replaces an existing mmsetotal with mmsetotal_2.
data$mmsetotal <- data$mmsetotal_2

data$COGmmse <- NA_real_
data$COGmmse[!is.na(data$mmsetotal) & data$mmsetotal >= 0] <-
  data$mmsetotal[!is.na(data$mmsetotal) & data$mmsetotal >= 0]

attr(data$COGmmse, "label") <- "Mini-mental state examination"
