# Scale ID: 			IQCODE
# Scale Name: 		IQCODE
# TILDA Variables: 	IQCODEtotal;IQCODEscore
# Dataset:      		TILDA Waves 3,4,5,6
# Author:
# Institution:  		The Irish Longitudinal Study on Ageing (TILDA)
# 
# Description:
# Cleans and codes up summed score from the Informant Questionnaire on Cognitive Decline in the Elderly - Short Form.
# 
# Version:      1.0
# Date:         2026-09-01
# Language:     R
#
# Assumption: the working data frame is called `data`.

ph_items <- paste0("ph", 148:163)

# Counts are computed before the raw -1 recode in the Stata source.
data$noresponse <- rowSums(sapply(ph_items, function(v) data[[v]] == 6), na.rm = TRUE)
data$responses <- rowSums(
  sapply(ph_items, function(v) data[[v]] %in% c(1,2,3,4,5,6)),
  na.rm = TRUE
)

# Recode raw -1 to missing.
for (v in ph_items) {
  data[[v]][!is.na(data[[v]]) & data[[v]] == -1] <- NA_real_
}

# Create IQCODE1-IQCODE16, additionally recoding 6 and 98-99 to missing.
iq_items <- paste0("IQCODE", 1:16)
for (i in seq_along(ph_items)) {
  data[[iq_items[i]]] <- data[[ph_items[i]]]
  x <- data[[iq_items[i]]]
  x[!is.na(x) & (x == 6 | (x >= 98 & x <= 99))] <- NA_real_
  data[[iq_items[i]]] <- x
}

# Stata's hh005 != 1 is true for Stata system missing; include R NA here
# to preserve that comparison behaviour as closely as possible.
eligible <- is.na(data$hh005) | data$hh005 != 1

data$IQCODEtotal <- NA_real_
tot <- rowSums(data[iq_items], na.rm = TRUE)
data$IQCODEtotal[eligible] <- tot[eligible]

data$IQCODEscore <- NA_real_
score_ok <- eligible & !is.na(data$noresponse) & data$noresponse <= 2 &
            !is.na(data$responses) & data$responses != 0
data$IQCODEscore[score_ok] <-
  data$IQCODEtotal[score_ok] / data$responses[score_ok]
