# /******************************************************************
# Scale ID:           STAI
# Scale Name:         State Anxiety Inventory
# TILDA Variables:    COGstai6_total; COGstai6_equiv20
# Dataset:            TILDA Wave 1-6
# Author:
# Institution:        The Irish Longitudinal Study on Ageing (TILDA)
#
# Description:
# Generates scoring for the Penn State Worry Questionnaire.
#
# Version:      1.0
# Date:         2026-09-01
# Language:     R
# ******************************************************************/
#
# Assumption: the working data frame is called `data`.

stai_items <- paste0("COGstateanxiety", 1:6)

# Raw 6-item total score.
# rowSums(..., na.rm = TRUE) mirrors Stata egen rowtotal().
data$COGstai6_total <- rowSums(data[stai_items], na.rm = TRUE)

# Require all six items to be answered.
data$COGstai6_missing <- rowSums(is.na(data[stai_items]))
data$COGstai6_total[data$COGstai6_missing > 0] <- NA_real_

attr(data$COGstai6_total, "label") <-
  "STAI-6 state anxiety total score (6-24)"


# 20-item equivalent score.
data$COGstai6_equiv20 <- data$COGstai6_total * (20 / 6)

attr(data$COGstai6_equiv20, "label") <-
  "STAI-6 state anxiety score, 20-item equivalent (20-80)"


# Checks.
summary(data[c("COGstai6_total", "COGstai6_equiv20")])
table(data$COGstai6_total, useNA = "ifany")


# Drop temporary variable.
data$COGstai6_missing <- NULL
